此插件用于上傳和下載文件。
我們需要打開(kāi)命令提示符并運(yùn)行以下命令來(lái)安裝插件。
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file-transfer
在本章中,我們將向您展示如何上傳和下載文件。 讓我們?cè)?strong> index.html 中創(chuàng)建兩個(gè)按鈕。
<button id = "uploadFile">UPLOAD</button> <button id = "downloadFile">DOWNLOAD</button>
事件監(jiān)聽(tīng)器將在onDeviceReady函數(shù)的index.js中創(chuàng)建。我們正在添加點(diǎn)擊事件和回調(diào)函數(shù)。
document.getElementById("uploadFile").addEventListener("click", uploadFile); document.getElementById("downloadFile").addEventListener("click", downloadFile);
此功能將用于從服務(wù)器下載文件到設(shè)備。 我們已將檔案上傳到 postimage.org ,讓操作更簡(jiǎn)單。你可能想使用自己的服務(wù)器。該函數(shù)放置在 index.js 中,并在按下相應(yīng)的按鈕時(shí)觸發(fā)。uri 是服務(wù)器下載鏈接, fileURI 是我們?cè)O(shè)備上DCIM文件夾的路徑。
function downloadFile() { var fileTransfer = new FileTransfer(); var uri = encodeURI("http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg"); var fileURL = "///storage/emulated/0/DCIM/myFile"; fileTransfer.download( uri, fileURL, function(entry) { console.log("download complete: " + entry.toURL()); }, function(error) { console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("download error code" + error.code); }, false, { headers: { "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" } } ); }
一旦按下下載按鈕,該文件將從 postimg.org 服務(wù)器下載到我們的移動(dòng)設(shè)備。 我們可以檢查指定的文件夾,看看 myFile 是否存在。
控制臺(tái)輸出看起來(lái)像這樣 -
現(xiàn)在讓我們創(chuàng)建將文件并將其上傳到服務(wù)器的函數(shù)。 再次,我們希望盡可能簡(jiǎn)化這一過(guò)程,因此我們將使用 posttestserver.com 在線服務(wù)器進(jìn)行測(cè)試。uri 值將會(huì)鏈接到發(fā)布到 posttestserver 。
function uploadFile() { var fileURL = "///storage/emulated/0/DCIM/myFile" var uri = encodeURI("http://posttestserver.com/post.php"); var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1); options.mimeType = "text/plain"; var headers = {'headerParam':'headerValue'}; options.headers = headers; var ft = new FileTransfer(); ft.upload(fileURL, uri, onSuccess, onError, options); function onSuccess(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); } function onError(error) { alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log("upload error target " + error.target); } }
現(xiàn)在我們可以按上傳按鈕來(lái)觸發(fā)此功能。我們將獲得控制臺(tái)輸出,確認(rèn)上傳是成功的。
現(xiàn)在我們可以按上傳按鈕來(lái)觸發(fā)此功能。我們將獲得控制臺(tái)輸出,確認(rèn)上傳是成功的。...
更多建議: