admin管理员组文章数量:1025259
I have looked high and low for a straight forward answer to this question.
I have an image loaded locally in a phone gap application in the following directory:
/image/test.png
I want to send this image to the server as part of a multi-part form using form data.
var formdata = new FormData();
I then append my JSON
formdata.append("json", JSON.stringify(request));
I then want to append the image and I tried using the following
var img = new Image();
img.src = './image/test.png';
formdata.append("file", img.src );
$.ajax(
{
url : "http://myserver:8080/myservlet",
type : "POST",
data : formdata,
processData : false,
contentType : false,
dataType : "json",
success : function(response)
{
console.log("success response:"+JSON.stringify(response));
},
error : function(jqXHR,textStatus,errorThrown)
{
var msg = "Error Sending File. Status: "+textStatus+" Error:"+errorThrown;
navigator.notification.alert(msg, null, "Error", "OK");
}
});
This if course is not working for me - what am I doing wrong.
I have looked high and low for a straight forward answer to this question.
I have an image loaded locally in a phone gap application in the following directory:
/image/test.png
I want to send this image to the server as part of a multi-part form using form data.
var formdata = new FormData();
I then append my JSON
formdata.append("json", JSON.stringify(request));
I then want to append the image and I tried using the following
var img = new Image();
img.src = './image/test.png';
formdata.append("file", img.src );
$.ajax(
{
url : "http://myserver:8080/myservlet",
type : "POST",
data : formdata,
processData : false,
contentType : false,
dataType : "json",
success : function(response)
{
console.log("success response:"+JSON.stringify(response));
},
error : function(jqXHR,textStatus,errorThrown)
{
var msg = "Error Sending File. Status: "+textStatus+" Error:"+errorThrown;
navigator.notification.alert(msg, null, "Error", "OK");
}
});
This if course is not working for me - what am I doing wrong.
Share Improve this question edited Dec 15, 2013 at 23:41 DavidC 1,8621 gold badge18 silver badges32 bronze badges asked Dec 15, 2013 at 22:42 simappsimapp 492 silver badges6 bronze badges4 Answers
Reset to default 3You may use this plugin to get base64 encoding of your local image then send it to server using ajax:
window.plugins.Base64.encodeFile(filePath, function(base64){
console.log('file base64 encoding: ' + base64);
//write down ajax code to send base64 string
});
you are trying to upload an image (=file) but in fact you are posting a string returned by img.src
. If you like to post your image you'll need to convert it to a string that can be posted. you can do this by loading your image into a canvas element and get call toDataUrl. However when using phonegap, I remend uploading the file through a filetransfer and add your additional post data to it...
function uploadPhoto(imageUrlToUpload) {
//alert('upload: '+imageUriToUpload);
var url=encodeURI(youruploadurl);
var params = new Object();
params.your_param_name = "something"; //add your additional post parameters here
var options = new FileUploadOptions();
options.headers={Connection: "close"};
options.fileKey = "file"; //depends on the api
options.fileName = imageUriToUpload.substr(imageUriToUpload.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false; //this is important to send both data and files
options.params = params;
var ft = new FileTransfer();
//what to do during the file transfer? lets show some percentage...
var status=$('yourselectorhere');//element in the dom that gets updated during the onprogress
ft.onprogress = function(progressEvent) {
var perc;
if (progressEvent.lengthComputable) {
perc = Math.ceil(progressEvent.loaded / progressEvent.total * 100);
status.html(perc+'%'+ '('+progressEvent.total+')');
}else{alert('not putable');}
};
ft.upload(imageUrlToUpload, url, success, fail, options);
}
function success(r) {
alert("Upload success: Code = " + r.responseCode);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
On phonegap you can use the FileTransfer plugin. On post PhoneGap 3 you have to include the plugin in your config.xml
<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />
Then to upload to the server do something like this:
var imageUploadSuccess = function (data) {
alert("Cool");
}
var imageUploadFail = function (error) {
alert("fail");
}
var params = new Object();
params.yourHttpParam = "My Param Value";
var url ="http://myserver./photo/upload";
var options = new FileUploadOptions();
options.fileName = "/image/test.png";
options.mimeType = "image/png";
options.fileKey = "file";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload("/image/test.png", url, imageUploadSuccess, imageUploadFail, options, true);
You need to use the FileTransfer
API, note that there are some problems with it at the time of writing (however they are being addressed.).
See the documentation here for details. http://docs.phonegap./en/3.2.0/cordova_file_file.md.html#FileTransfer
Here's a quick example:
var fileURI = // imageURI returned by the CameraAPI.
var success = 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 = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
// The following options are to attempt circumvention of the
// FileTransfer.upload issues in the linked Cordova thread.
// Note that they are reportedly, not always effective.
options.headers={Connection: "close"};
options.chunkedMode = false;
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server./upload.php"), success, fail, options);
You will need to enable the file and file-transfer plugins in your Android Manifest.
<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />
A quick note about the known problems... uploading will fail on every other subsequent upload (ie. success, fail, success, fail, etc...) - Note that this problem has affected iOS and Android (I can't speak for BB or other platforms.) AFAIK, Android is still affected, but I remend you read the thread and keep an eye on it.
There are remended solutions/workarounds, however they are also reported to fail (ie. turn off chunked mode and attempting to force close the connection.)
Until there is a reliable fix, it is better to simply keep an attempted connection counter, and handle the even numbered fails as cause to immediately re-try. (nasty, but necessary.)
I have looked high and low for a straight forward answer to this question.
I have an image loaded locally in a phone gap application in the following directory:
/image/test.png
I want to send this image to the server as part of a multi-part form using form data.
var formdata = new FormData();
I then append my JSON
formdata.append("json", JSON.stringify(request));
I then want to append the image and I tried using the following
var img = new Image();
img.src = './image/test.png';
formdata.append("file", img.src );
$.ajax(
{
url : "http://myserver:8080/myservlet",
type : "POST",
data : formdata,
processData : false,
contentType : false,
dataType : "json",
success : function(response)
{
console.log("success response:"+JSON.stringify(response));
},
error : function(jqXHR,textStatus,errorThrown)
{
var msg = "Error Sending File. Status: "+textStatus+" Error:"+errorThrown;
navigator.notification.alert(msg, null, "Error", "OK");
}
});
This if course is not working for me - what am I doing wrong.
I have looked high and low for a straight forward answer to this question.
I have an image loaded locally in a phone gap application in the following directory:
/image/test.png
I want to send this image to the server as part of a multi-part form using form data.
var formdata = new FormData();
I then append my JSON
formdata.append("json", JSON.stringify(request));
I then want to append the image and I tried using the following
var img = new Image();
img.src = './image/test.png';
formdata.append("file", img.src );
$.ajax(
{
url : "http://myserver:8080/myservlet",
type : "POST",
data : formdata,
processData : false,
contentType : false,
dataType : "json",
success : function(response)
{
console.log("success response:"+JSON.stringify(response));
},
error : function(jqXHR,textStatus,errorThrown)
{
var msg = "Error Sending File. Status: "+textStatus+" Error:"+errorThrown;
navigator.notification.alert(msg, null, "Error", "OK");
}
});
This if course is not working for me - what am I doing wrong.
Share Improve this question edited Dec 15, 2013 at 23:41 DavidC 1,8621 gold badge18 silver badges32 bronze badges asked Dec 15, 2013 at 22:42 simappsimapp 492 silver badges6 bronze badges4 Answers
Reset to default 3You may use this plugin to get base64 encoding of your local image then send it to server using ajax:
window.plugins.Base64.encodeFile(filePath, function(base64){
console.log('file base64 encoding: ' + base64);
//write down ajax code to send base64 string
});
you are trying to upload an image (=file) but in fact you are posting a string returned by img.src
. If you like to post your image you'll need to convert it to a string that can be posted. you can do this by loading your image into a canvas element and get call toDataUrl. However when using phonegap, I remend uploading the file through a filetransfer and add your additional post data to it...
function uploadPhoto(imageUrlToUpload) {
//alert('upload: '+imageUriToUpload);
var url=encodeURI(youruploadurl);
var params = new Object();
params.your_param_name = "something"; //add your additional post parameters here
var options = new FileUploadOptions();
options.headers={Connection: "close"};
options.fileKey = "file"; //depends on the api
options.fileName = imageUriToUpload.substr(imageUriToUpload.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false; //this is important to send both data and files
options.params = params;
var ft = new FileTransfer();
//what to do during the file transfer? lets show some percentage...
var status=$('yourselectorhere');//element in the dom that gets updated during the onprogress
ft.onprogress = function(progressEvent) {
var perc;
if (progressEvent.lengthComputable) {
perc = Math.ceil(progressEvent.loaded / progressEvent.total * 100);
status.html(perc+'%'+ '('+progressEvent.total+')');
}else{alert('not putable');}
};
ft.upload(imageUrlToUpload, url, success, fail, options);
}
function success(r) {
alert("Upload success: Code = " + r.responseCode);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
On phonegap you can use the FileTransfer plugin. On post PhoneGap 3 you have to include the plugin in your config.xml
<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />
Then to upload to the server do something like this:
var imageUploadSuccess = function (data) {
alert("Cool");
}
var imageUploadFail = function (error) {
alert("fail");
}
var params = new Object();
params.yourHttpParam = "My Param Value";
var url ="http://myserver./photo/upload";
var options = new FileUploadOptions();
options.fileName = "/image/test.png";
options.mimeType = "image/png";
options.fileKey = "file";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload("/image/test.png", url, imageUploadSuccess, imageUploadFail, options, true);
You need to use the FileTransfer
API, note that there are some problems with it at the time of writing (however they are being addressed.).
See the documentation here for details. http://docs.phonegap./en/3.2.0/cordova_file_file.md.html#FileTransfer
Here's a quick example:
var fileURI = // imageURI returned by the CameraAPI.
var success = 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 = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
// The following options are to attempt circumvention of the
// FileTransfer.upload issues in the linked Cordova thread.
// Note that they are reportedly, not always effective.
options.headers={Connection: "close"};
options.chunkedMode = false;
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server./upload.php"), success, fail, options);
You will need to enable the file and file-transfer plugins in your Android Manifest.
<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />
A quick note about the known problems... uploading will fail on every other subsequent upload (ie. success, fail, success, fail, etc...) - Note that this problem has affected iOS and Android (I can't speak for BB or other platforms.) AFAIK, Android is still affected, but I remend you read the thread and keep an eye on it.
There are remended solutions/workarounds, however they are also reported to fail (ie. turn off chunked mode and attempting to force close the connection.)
Until there is a reliable fix, it is better to simply keep an attempted connection counter, and handle the even numbered fails as cause to immediately re-try. (nasty, but necessary.)
本文标签: javascriptSend Locally Stored Image to Server Via AjaxStack Overflow
版权声明:本文标题:javascript - Send Locally Stored Image to Server Via Ajax - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745613681a2159158.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论