Search code examples
androidcordovacordova-plugins

Cordova Android: Empty request while uploading file using official cordova-plugin-file-transfer


Trying to upload a file to a server using the official cordova-plugin-file-transfer provided by Apache at https://github.com/apache/cordova-plugin-file-transfer.

Created an empty cordova project, setup file picker (https://github.com/don/cordova-filechooser) and file uploader, and ran the following code:

function servUpload(fileURL) {
    var win = function (r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
    }

    var fail = function (error) {
        alert("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
    }

    var options = new FileUploadOptions();
    options.fileKey = "upfile";
    options.fileName = "test.jpg";
    options.mimeType = "image/jpeg";
    options.httpMethod = "POST";

    var params = {};
    params.value1 = "test";
    params.value2 = "param";

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(fileURL, encodeURI("http://example.com/test.php"), win, fail, options);
}

function getFile() {
    fileChooser.open(function(uri){
        //alert(uri);
        //document.getElementById('img1').setAttribute('src', uri);
        console.log(uri);
        servUpload(uri);
    }, function(err){
        console.log(err);
    });
}
getFile();

(Note the post params I set).

My test.php contains the following (just echos back all of the file, post and get vars).

<?php
print_r($_FILES);
print_r($_POST);
print_r($_GET);
?>

The code runs fine, I can pick a file and it seems to take a bit to attempt to upload. But without any error the server picks up that it has not received any info from the client (no files, nor the POST params I set in the code):

Response = Array
(
)
Array
(
)
Array
(
)

A simple post request works though:

var http = new XMLHttpRequest();
var url = "http://example.com/test.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        console.log(http.responseText);
    }
}
http.send(params);

This returns:

Array
(
)
Array
(
    [lorem] => ipsum
    [name] => binny
)
Array
(
)

I'm at a loss for what I can do, I've made sure that the file picker actually works (I've been testing with an image file and tested that I can set an <img> element with the image as its source).

Any ideas? Thanks in advance.


Solution

  • Figured it out, wasn't a problem on cordova's end, my LEMP wasn't setup right. Cordova code works perfectly.