无法使用Cordova FileTransfer

时间:2016-12-03 19:56:12

标签: android cordova plugins upload file-transfer

我正在尝试使用FileTransfer Cordova插件(https://github.com/apache/cordova-plugin-file-transfer)上传方法上传文件。最后我几乎复制了项目页面上提到的示例,但仍然没有成功 - 该方法触发成功回调函数,但目标脚本不接收文件或任何参数。我的代码是:

通话功能:

var fleNme = TOP_APP_DIR + "/config/config.json";

fileAPI.readFile(fleNme, function (data) {
    console.log("File content: " + data); // just to meake sure the file exists and it contains some data

    fileAPI.uploadFile("http://posttestserver.com/post.php", fleNme, { par1: "test", par2: "test2" }, null, function (r) {
            console.log("Successful upload...");
            console.log(JSON.stringify(r));
    });
});

上传功能:

fileAPI.uploadFile = function (url, filePath, params, progressFunc, successCallback, failCallback, FStype) {
    if (typeof failCallback === "undefined" || failCallback === null)
        failCallback = fileAPI.defaultErrorCallback;

    // getFileEntry method is used for reading the file before call the upload method, so it's OK
    fileAPI.getFileEntry(filePath, function (fileEntry) {
        var fileURL = fileEntry.toURL();

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

        if(typeof params === "undefined" || params === null)
            params = {};

        options.params = params;

        var ft = new FileTransfer();

        ft.upload(fileURL, encodeURI(url), successCallback, failCallback, options);
    }, failCallback,FStype,false);
};

我的控制台中的输出是:

  • 文件内容:{“version”:9,“timeStamp”:1480793843086,“language”:“cs”........
  • 成功上传......
  • {“response”:“成功转储0个后置变量。\ n在http://www.posttestserver.com/data/2016/12/03/11.41.062096548295处查看\ n正在查找正文为0个字符长。”,“responseCode”:200,“objectId”:“”,“bytesSent” :522}
来自posttestserver.com的

日志是:

Time: Sat, 03 Dec 16 11:41:06 -0800
Source ip: 31.30.45.209

Headers (Some may be inserted by server)
REQUEST_URI = /post.php
QUERY_STRING = 
REQUEST_METHOD = POST
GATEWAY_INTERFACE = CGI/1.1
REMOTE_PORT = 48730
REMOTE_ADDR = 31.30.45.209
HTTP_ACCEPT_ENCODING = gzip
HTTP_CONNECTION = close
HTTP_HOST = posttestserver.com
HTTP_USER_AGENT = Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-T320     Build/KOT49H)
CONTENT_TYPE = multipart/form-data; boundary=+++++
UNIQUE_ID = WEMf0kBaMGUAAFmEWtgAAAAK
REQUEST_TIME_FLOAT = 1480794066.2475
REQUEST_TIME = 1480794066

No Post Params.
Empty post body.

== Multipart File upload. ==
Received 0 file(s)

我的目标是Cordova CLI 6.1.1。我花了一整天尝试不同的方法,但总是得到相同的结果。我在3种不同的Android设备上验证了代码 - HTC 10,三星Galaxy Tab SM-T320和一些旧的Prestigio手机 - 结果相同。知道什么是错的吗?

1 个答案:

答案 0 :(得分:1)

我发现chunkedMode的默认设置存在很多问题(true)。切换到options.chunckedMode = false应该有助于解决问题。