通过Ajax将本地存储的映像发送到服务器

时间:2013-12-15 22:42:43

标签: javascript ajax json html5 cordova

我对这个问题的直接回答看起来很高。

我在以下目录中的手机间隙应用程序中本地加载了图像:

/image/test.png

我想使用表单数据将此图像作为多部分表单的一部分发送到服务器。

var formdata = new FormData();

然后我追加我的JSON

formdata.append("json", JSON.stringify(request));

然后我想附加图片,我尝试使用以下

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");
  }
});

这个课程对我不起作用 - 我做错了什么。

4 个答案:

答案 0 :(得分:3)

您可以使用此plugin获取本地映像的base64编码,然后使用ajax将其发送到服务器:

window.plugins.Base64.encodeFile(filePath, function(base64){
        console.log('file base64 encoding: ' + base64);
        //write down ajax code to send base64 string
    });

答案 1 :(得分:0)

在phonegap上,您可以使用FileTransfer插件。在PhoneGap 3之后,您必须在config.xml中包含该插件

 <gap:plugin name="org.apache.cordova.file" />
 <gap:plugin name="org.apache.cordova.file-transfer" />

然后上传到服务器执行以下操作:

  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.com/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);

答案 2 :(得分:0)

您需要使用FileTransfer API,请注意在撰写本文时存在一些问题(however they are being addressed.)。

有关详细信息,请参阅此处的文档。 http://docs.phonegap.com/en/3.2.0/cordova_file_file.md.html#FileTransfer

这是一个简单的例子:

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.com/upload.php"), success, fail, options);

您需要在Android Manifest中启用文件和文件传输插件。

<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />

关于已知问题的快速说明...... 上传将在每次其他后续上传时失败(即成功,失败,成功,失败等等) - 请注意,此问题有受影响的iOS和Android(我无法代替BB或其他平台。)AFAIK,Android仍然受到影响,但我建议您read the thread并密切关注它。

有推荐的解决方案/解决方法,但是也会报告它们失败(即关闭分块模式并尝试强行关闭连接。)

在有可靠的修复之前,最好简单地保留一个尝试的连接计数器,并处理偶数编号的失败作为立即重新尝试的原因。 (讨厌,但必要。)

答案 3 :(得分:0)

您正在尝试上传图片(=文件),但实际上您正在发布img.src返回的字符串。如果您想发布图片,则需要将其转换为可以发布的字符串。您可以通过将图像加载到canvas元素并调用toDataUrl来完成此操作。但是,在使用phonegap时,我建议您通过文件传输上传文件并将其他帖子数据添加到其中...

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 computable');}
    };

    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);
}