2015-10-14 35 views
0

我在Windows Phone上使用Phonegap,並且需要創建一個文件,然後才能上傳到服務器(我通常會POST數據,但是我使用的服務器由於一些不明原因,對POST請求的大小有限制)。有沒有人對我如何實現這一目標有任何想法?在Windows Phone上創建文件並使用PhoneGap上傳

回答

0

它看起來像這樣可以使用W3C文件API(available in Cordova)和Cordova File Transfer plugin的組合。

1)安裝File Transfer plugin

科爾多瓦插件添加科爾多瓦 - 插件 - 文件傳輸

2)使用類似的代碼以下

我會試圖使用類似async的東西,儘管使這更具可讀性。

注意:此代碼假定文件以附件形式上載,名爲「文件」(您需要查看服務器上的文件)。

// 1) Request access to the file system 
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){ 

    // 2) Create a new file 
    fileSystem.root.getFile("file.json", {create: true, exclusive: false}, function(fileEntry){ 

     console.log("We now have access to the file: " + fileEntry.fullPath + " -- " + fileEntry.toURL()); 

     // 3) Create a file write object 
     fileEntry.createWriter(function(writer){ 

      // 4) Write the information to the file 
      writer.write("File contents go here"); 
      writer.onwriteend = function(evt) { 

       // 5) We've written the data to the file. Now upload. 
       var url = "http://serverurl.com"; 
       var fileURL = fileEntry.toURL(); // Local file URL 

       var options = new FileUploadOptions(); 
       options.fileKey = "file"; 
       options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); 
       options.mimeType = "text/plain"; 

       // Add any headers, if necessary 
       var headers = { 
         "HEADER": "value" 
       }; 
       options.headers = headers; 

       console.log("Uploading file at: " + fileEntry.fullPath + " to " + fileURL); 
       var ft = new FileTransfer(); 
       ft.upload(fileURL, encodeURI(url), function(r){ 

        // Upload was successful. You can now do something with the response 
        // This code assumes the response is in JSON format. 
        console.log("Code = " + r.responseCode); 
        console.log("Response = " + r.response); 
        console.log("Sent = " + r.bytesSent); 

        var response = JSON.parse(r.response); 
        alert(response.success); 

       }, 
       function(error){ 
        // An error occurred when attempting to upload. Refer to the following page for an 
        // explanation of the error codes: https://github.com/apache/cordova-plugin-file-transfer 
        console.log("An error has occurred: Code = " + error.code); 
        console.log("upload error source " + error.source); 
        console.log("upload error target " + error.target); 

        alert("Unable to upload file"); 
       }, options); 

      }; 

     }, function(error){ 
      console.log("Unable to create file writer: " + error); 
     }); 

    }, function(error){ 
     console.log("Unable to create file: " + error); 
    }); 
}, function(error){ 
    console.log("Unable to access file system: " + error); 
}); 
相關問題