Now this has taken me so long to figure out, I almost gave up so many times but hey I eventually slew the dragon. I went to so many different solutions and they only took me so far then I got stuck.
Issue:
I needed to upload photos stored on my Android device to a PHP server, using Cordova File Transfer plugin.
Technology:
- Cordova: 3.6
- Android 4.0.3
- File Transfer Plugin
JavaScript:
function uploadPhoto(fileURL) { var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); options.mimeType = "text/plain"; var params = {}; params.value1 = "test"; params.value2 = "param"; options.params = params; var ft = new FileTransfer(); ft.upload(fileURL, encodeURI("http://yourdomain.com/upload.php"), win, fail, options); } function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); alert(r.response); } function fail(error) { alert("error"); switch (error.code) { case FileTransferError.FILE_NOT_FOUND_ERR: alert("Photo file not found"); break; case FileTransferError.INVALID_URL_ERR: alert("Bad Photo URL"); break; case FileTransferError.CONNECTION_ERR: alert("Connection error"); break; } alert("An error has occurred: Code = " + error.code); }
PHP Code:
if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . ""; } else { $new_image_name = strtolower($_FILES['file']['name']); move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name); }
Special Notes:
Make sure you have an upload folder, also this code will use the name of the file stored on the Android Device.
This solution worked for me if you have any questions I will try to answer the best I can.