I am doing project in android phonegap.Here I want to upload images and videos to remote server.
I used the following link.
http://zacvineyard.com/blog/2011/03/upload-a-file-to-a-remote-server-with-phonegap
I also change some options like options.chunkedMode = false ,android:debuggable="true" and
. But still it shows error code 3.I am using the cordova-2.0.0.js version.Can anyone suggest some answer.
My js code is
**
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Do cool things here...
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},
{quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "url of ther server/upload.php", win, fail, options, true);
console.log("H");
}
function win(r) {
console.log("HIIIIIiiii");
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("There is something");
alert("An error has occurred: Code = " + error.code);
}
</script>
**
and my php code is
<?php
print_r($_FILES);
$new_image_name = "namethisimage.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name);
?>
Thanks.
Have you added the URL in question to your whitelist?
e.g. in config.xml do you have something like:
<access origin="www.myurl.com" subdomains="true" />
or
<access origin="*" />
which allows all URLs.
Error code 3 is a FileTransferError.CONNECTION_ERR by the way.
Related
Issue
I have a page where users can upload files with the help of FormData and an XMLHttpRequest.
Uploading the file works fine. But the upload.onprogress is only working when uploading from an HTTP connection.
HTTPS
HTTP
I've tested this on Heroku and on an Amazon EC2 instance. But it's always the same:
Progress is shown when uploading via HTTP
Progress event is never triggered when uploading via HTTPS
Javascript (Angular 7)
const xhr = new XMLHttpRequest();
let progress = 0;
/** THIS EVENT IS NOT WORKING WITH HTTPS */
xhr.upload.onprogress = (event: ProgressEvent) => {
if (event.lengthComputable) {
progress = 100 * (event.loaded / event.total);
}
};
xhr.responseType = 'json';
xhr.open('POST', `${API_URL}/${this.API_PATH}/upload`, true);
xhr.setRequestHeader('authorization', this.authService.getAuthToken());
xhr.send(payload);
xhr.onload = () => {
observer.next(xhr.response);
observer.complete();
};
Node.Js
const busboyBodyParser = require('busboy-body-parser');
app.use(busboyBodyParser())
const busboy = new Busboy({ headers: req.headers })
busboy.on('finish', async () => {
const fileData = req.files.file
const fileId = req.body.fileId
const params = {
Body: fileData.data,
Bucket: awsConfig.bucket,
ContentType: fileData.mimetype,
Key: fileId,
StorageClass: 'ONEZONE_IA',
}
awsConfig.s3.upload(params, (err, data) => { /* ... */ }
})
req.pipe(busboy)
What I've also tried
I also tried to use the .addEventListener syntax for listening for progress:
xhr.upload.addEventListener("progress", uploadProgress, false);
But this didn't work, either.
Source Code
Node.Js (server.js)
Node.Js (upload-file.js)
Angular Service (editor-file.service.ts)
Notes
Please note, that I have already asked a question about this topic. But I got no working answer and I really need this to work.
Old question: XHR upload onprogress Event not Working on HTTPS Connection
It's important to set Listener between:
xhr.open('POST'...);
...put you listener here....
xhr.send(data)
In this case it gonna work!
I'm doing just the same with one of my webapps but without any angular, just JS and PHP.
My xhr works like a charm and is looking like this:
var totalSize = 0;
var xhr = new XMLHttpRequest(); // den AJAX Request anlegen
xhr.open('POST', 'data/upload.php'); // Angeben der URL und des Requesttyps
xhr.upload.addEventListener("progress", handleProgress);
xhr.addEventListener("load", handleComplete);
and this my handleProgess method:
handleProgress = function(event){
var progress = totalProgress + event.loaded;
document.getElementById('progress').innerHTML = 'Aktueller Fortschritt: ' + ((progress - totalSize < 0) ? Math.floor(progress / totalSize * 10000) / 100 : 100) + '%';
}
As I've tried to reproduce this problem, I didn't face the same issue. Could you please check below simple Heroku app that I've created to test this specific problem? Also, if there is any missing part that I am not seeing, please inform me.
Heroku Test-Purpose App: https://erdsav-test-app.herokuapp.com/
Below is the JS code that I am tried to build on top of your code and it simply uploads the zip data and downloads it afterwards (cannot store on Heroku because of having Ephemeral filesystem) to ensure that the file is uploaded successfully;
import { Observable } from "../js/Observable.js";
document.addEventListener("DOMContentLoaded", function(event) {
var progressBar = document.getElementById("progress"),
fileNameSpan = document.getElementById("file_name"),
fileSizeSpan = document.getElementById("file_size"),
fileUploadComp = document.getElementById("file_upload"),
loadButton = document.getElementById("upload_button"),
displaySpan = document.getElementById("progress_display"),
fileDetails = document.getElementById("file_details"),
selectButton = document.getElementById("select_button"),
formData = null;
function hideElements(){
fileDetails.style.display = "none";
}
function showElements(){
fileDetails.style.display = "block";
}
function upload(payload, fileName){
return new Observable(observer => {
const xhr = new XMLHttpRequest();
let progress = 0;
/** THIS EVENT IS NOT WORKING WITH HTTPS */
xhr.upload.onprogress = (event => {
if (event.lengthComputable) {
progressBar.max = event.total;
progressBar.value = event.loaded;
progress = Math.floor((event.loaded / event.total) * 100);
displaySpan.innerText = progress + '%';
observer.next(progress);
}
});
xhr.upload.onloadstart = function(e) {
progressBar.value = 0;
displaySpan.innerText = '0%';
}
xhr.upload.onloadend = function(e) {
progressBar.value = e.loaded;
loadButton.disabled = false;
loadButton.innerHTML = 'Start Upload Process';
}
xhr.responseType = 'blob';
xhr.open('POST', "https://erdsav-test-app.herokuapp.com/upload.php", true);
xhr.send(payload);
xhr.returnedFileName = fileName;
xhr.onload = () => {
download(xhr.response, xhr.returnedFileName, "application/zip");
observer.next(100);
observer.complete();
};
});
}
function showUploadedFile(file){
var fileName = file.name;
var fileSize = file.size;
fileNameSpan.innerText = fileName;
fileSizeSpan.innerText = Math.floor(fileSize / 1000) + ' KB';
}
function buildFormData(file) {
if (formData) {
formData.append("file", file);
}
return formData;
}
hideElements();
if (window.FormData) {
formData = new FormData();
}
else{
alert("FormData is not supported in this browser!");
}
fileUploadComp.onchange = function(){
var file = fileUploadComp.files[0];
if(file){
showElements();
showUploadedFile(file);
}
else{
hideElements();
}
}
selectButton.addEventListener("click", function(e){
fileUploadComp.value = "";
hideElements();
fileUploadComp.click();
e.preventDefault();
});
loadButton.addEventListener("click", function(e) {
if(fileUploadComp.files !== undefined && fileUploadComp.files.length > 0){
this.disabled = true;
this.innerHTML = "Uploading. Please wait...";
var obs = upload(buildFormData(fileUploadComp.files[0]), fileUploadComp.files[0].name);
obs.subscribe(
function valueHandler(value){
console.log("UPLOADING");
if(value){
console.log(value);
}
},
function errorHandler(err){
console.log("THERE IS AN ERROR");
},
function completeHandler(){
console.log("COMPLETE");
}
);
}
else{
alert("No file is selected");
}
e.preventDefault();
});
});
PHP side
<?php
if ($_FILES['file']['error'] != $UPLOAD_ERR_OK) {
//writeLog($_FILES['file']['error']);
echo 'An error occurred!';
exit();
}
else {
$filePath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
if (file_exists($filePath)) {
ob_start();
$fileSize = readfile($filePath);
$content = ob_get_clean();
header('Content-Type: application/octet-stream;');
header("Content-Disposition: attachment; filename=\"" . $fileName . "\"");
header('Expires: 0');
header('Pragma: no cache');
header('Content-Length: ' . $fileSize);
echo $content;
}
else{
echo 'File is not found';
exit();
}
}
?>
HTML page source
<!DOCTYPE html>
<html lang="en">
<title>ProgressBar Progress Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="ProgressBar Progress Test">
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" id="file_upload" accept="application/zip" style="width:0px" />
<button id="select_button">Choose File to Upload</button>
<progress id="progress" value="0"></progress>
<span id="progress_display"></span>
<button type="submit" id="upload_button">Start Upload Process</button>
</form>
<div id="file_details" style="display: none">
<h3>Selected File Details</h3>
<span id="file_name"></span><br>
<span id="file_size"></span>
</div>
<script type="module" src="js/Observable.js"></script>
<script src="js/download.js"></script>
<script type="module" src="js/main.js"></script>
</body>
</html>
Below image is captured by slowing the network to see the current percentage while uploading process continues;
Browsers used in testing;
Firefox Developer Edition 67.0b13 (64-bit/Up-to-date)
Google Chrome 74.0.3729.108 (64-bit/Up-to-date)
Now in 2022
The 2016's specifications are outdated, here is the new standard for XMLHttpRequest.
The upload is a getter that returns an XMLHttpRequestUpload object
The XMLHttpRequestUpload object implements the XMLHttpRequestEventTarget interface, which handles the onprogress event.
Now here's what MDN says about this:
Note: The spec also seems to indicate that event listeners should be attached after open(). However, browsers are buggy on this matter, and often need the listeners to be registered before open() to work.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Now its almost 6 days and I am trying to fix image upload issue in cordova-php but not able to fix it. I tried multiple solutions from Google and Stack Overflow. But none of them is working for me.
I am using the below code as front end.
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://sample.com/mobile_app/upload_img.php" />
</div>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="fileUpload";
options.httpMethod="POST";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// var op;
//op = new FileUploadOptions();
options.headers = {
Connection: "close"
};
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.response+" bytes uploaded."; alert(r.response);
}, function(error) {
alert(r.response);
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
And here comes the backend (PHP) code.
<?php
header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
header("content-type: image/png");
// Directory where uploaded images are saved
$dirname = "user_img";//"mobile_app/user_img";
var_dump($_POST);
$new_image_name = urldecode($_FILES["fileUpload"]["name"]).".png";
// If uploading file
//echo $_FILES;
echo $new_image_name;
print_r($_FILES["fileUpload"]);
if ($_FILES) {
print_r($_FILES);
//mkdir ($dirname, 0777, true);
move_uploaded_file($_FILES["fileUpload"]["tmp_name"],$dirname."/".$_FILES["fileUpload"]["name"]);
}
// If retrieving an image
else if (isset($_GET['image'])) {
$file = $dirname."/".$_GET['image'];
// Specify as jpeg
header('Content-type: image/jpeg');
// Resize image for mobile
list($width, $height) = getimagesize($file);
$newWidth = 120.0;
$size = $newWidth / $width;
$newHeight = $height * $size;
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($resizedImage, null, 80);
}
// If displaying images
else {
$baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
$images = scandir($dirname);
$ignore = Array(".", "..");
if ($images) {
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "Image: ".$curimg."<br>";
echo "<img src='".$baseURI."?image=".$curimg."&rnd=".uniqid()."'><br>";
}
}
}
else {
echo "No images on server";
}
}
?>
I found $_FILES is empty I am getting Array() only. I don't know what is wrong with the code because same code i have seen on multiple question and examples.
I used two web servers but same result.
user_img folder have 777 access.
Finally I fixed the issue, the fix was simple.
The url I had given was http://sample.com/upload_img.php. I just needed to add www in the url. So, working URL is http://www/sample.com/upload_img.php.
It fixed the issue.
I am using phonegap 3.0.0
And in the process of attempting to upload a file to the server I am getting a couple things that are unexpected. First thing, a script error:
Error: SyntaxError: Unexpected token ':' line 624 of phonegap.js
(which I think is a lot older version of the js to begin with, as I could only find one on github)
Next thing I am getting which I don't see why/how this would prompt when I have never seen it on other apps.. is a little alert dialog:
When I click OK on the dialog thats when it attempts to carry out the rest of the script, and gives me the above error.
and the script I am using to upload is based almost to the letter the same as the one found on the phonegap site.. http://docs.phonegap.com/en/3.0.0/cordova_file_file.md.html#File
$('#select_photo').on('click', function()
{
$('#choice_of_file').click();
});
$('#upload_photo').on('click', function()
{
if(fmr.nullCheck($('#choice_of_file').val()) == true)
{
alert('Please Choose a Photo');
}
else
{
uploadPhoto($('#choice_of_file').val());
}
});
// Wait for device API libraries to load
//
(function(){document.addEventListener("deviceready", onDeviceReady, false);})();
// device APIs are available
//
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(domainURL+'upload/wizard/'+MembId), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
the HTML for the form its reading..
<div style="position:absolute;top:-2000px;left:-2000px;background-color:#FFF;z-index:0" id="hide_file_input">
<form enctype="multipart/form-data" id="upload_profile_image" action="#none" method="post">
<input type="file" id="choice_of_file" name="choice_of_file">
</form>
</div>
Filekey should be the name attribute of file field
options.fileKey="choice_of_file";
Also it will be better if you can call deviceready before all functions are executed and put navigator.camera.getPicture in the onclick event of file field
Following this yet unanswered question I ran some tests to see where the problem is - in my side or in the server side.
So taking into account it might be a image codec problem, I have tried to upload a text/plain file to my server using post method.
First, I made sure the file exists by calling readAsText() method:
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("textfile.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Read as data URL");
alert(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Read as text");
alert(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
alert(evt.target.error.code);
}
After I get an alert with text file URL and text file content, I know this is my file. Now I'm uploading it:
function gotFile(file){
// alert('gotFile')
// readDataUrl(file);
// readAsText(file);
alert(file.fullPath)
uploadText(file.fullPath)
}
function uploadText(fileURI) {
alert('uploading file...')
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("http_status = " + error.http_status);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("https://mysecureurl.com/?filename="+options.fileName), win, fail, options);
}
I get fileTransfer error code 1 (file not found) and http status code 411 (malformed request).
I have all the permission including fileTransfer in my android project and also <access origin="*"/>. My server administrator says he gets the request but something is broken in the middle when I am sending file from phonegap (unlike normal browser requests) and he couldn't figure out what is it.
I am really stuck here. Is there any PhoneGap limitation I am not aware of? Or is there anyway to capture phone's http body request so I could debug it?
The problem is with content-type. Phonegap sets Content-Type: multipart/form-data;boundary=+++++ omitting the whitespace in between. Some servers can be picky with this. I solved the issue by rewriting this header and adding a whitespace as follows: Content-Type: multipart/form-data; boundary=+++++. Although this sounds like a hack, and solves the issue for me, this change needs to be incorporated into phonegap Android library in future releases.
It just happend on Android platform and fine on iOS, so try to set options.chunkedMode=false just on Android (the chunkedMode options default is true). see https://github.com/apache/cordova-plugin-file-transfer/pull/141#issuecomment-291776345
I am trying to upload a file to my server with Phonegap. I am currently stuck when an error that says:
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The HTML + Javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<title>File Transfer Example</title>
</head>
<body>
<button id="uploadPhotoButton">Upload a Photo</button>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript">
$(document).one("pause", function () {
console.log('Paused.');
});
$(document).one("resume", function () {
console.log('Resumed.');
});
$(document).one("deviceready", function () {
console.log('Device is ready.');
});
$(document).one("backbutton", function () {
console.log('Back button pressed.');
});
$(document).ready(function () {
console.log('DOM is ready.');
$(document).on("click", "#uploadPhotoButton", function (e) {
console.log('clicked button');
getImage();
});
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", 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("An error has occurred: Code = " = error.code);
}
});
</script>
</body>
</html>
The complete error log.
GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html
Log:"clicked button"
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0).
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0).
INFO: AppDeactivated
INFO: AppActivated
Log:"Paused."
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0).
Log:"Resumed."
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0).
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0).
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment"
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0).
Does anyone have an idea on how to make this work?
Thanks!
W
I'm thinking that you are malforming your options value. Do you need to pass JSON or an actual object?
Right now you are passing an array with text in it.
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The error seems to involve deserialization issues.
Put your getImage, uploadImage, win, fail outside of $(document).ready 's inline function call.
Reference to win and fail are actually closure, and phone gap gets it as null when it is trying to access those methods directly. Phonegap is probably expecting a global function instead of hidden function inside a function.
PhoneGap's executes its code out side javascript context, what may work in true javascript fashion may not work correctly with phonegap.
I had a problem similar to yours. I solved this, changing mimeType parameter to 'text/plain'.
Do you use params to send? If it's false I think you need send empty params.
I had this problem before, try to prepare the image in the html first, and dont take it directly from the navigator, it may not saving the taken photo in it cash ;)
In my solution I suppose to have an image tage with id ='camera_image'
img id='camera_image'...
Then i set all the variables of the image in it and I upload it (as you will see in the following code).
here's the 2 functions i used:
function takephoto(){
navigator.camera.getPicture(
function(uri){
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
alert("Success");
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
}
for choosing an existing photo:
function choosephoto(){
navigator.camera.getPicture(
function(uri) {
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("please select a pic first");
return;
}
}
in the upload function:
function uploadPhoto(img) {
imageURI = img.src ...
ps: sorry for the formatting of my code, it doesn't fix well.