繁体   English   中英

将图像附加到Ajax POST请求数据以进行Web服务调用

[英]Attach Image to ajax POST request data for web service call

我正在尝试(到目前为止未成功)将文件(图像)附加到JSON数据以调用Web服务中的方法。

我发现一些有关仅发送图像而不发送图像作为json数据对象一部分的帖子。

如果我将“ imageFile”保留为空,则该调用有效。

 $("#butSubmit").click(function(){ var files = document.getElementById('files').files; var file = files[0]; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url:"http://localhost:8080/SampleApp/api/users/add", data: JSON.stringify({"description":"test2","title":"testest2","uploaderName":"seren","imageFile":file}) }); }); 

在Web服务端,我正在调用此方法:

  @Path("/add") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public void addUser(Picture picture){ userService.persistPicture(picture); } 

与此图片类的构造函数一起使用:

  @JsonCreator public Picture( @JsonProperty("description") String description, @JsonProperty("title") String title, @JsonProperty("uploaderName") String uploaderName, @JsonProperty("imageFile") byte[] imageFile) { this.uploaderName = uploaderName; this.title = title; this.description = description; this.imageFile = (byte[]) imageFile; } 

希望您能指出正确的方向!

提前谢谢!

利用javascript中可用的FileReader对象-HTML 5 File Api( 浏览器支持

    var files = [];

    $("input[type=file]").change(function(event) {
      $.each(event.target.files, function(index, file) {
        var reader = new FileReader();
        reader.onload = function(event) {  
          object = {};
          object.filename = file.name;
          object.data = event.target.result;
          files.push(object);
        };  
        reader.readAsDataURL(file);
      });
    });

//post file using ajax call
$.each(files, function(index, file) {
    $.ajax({url: "/ajax-upload",
          type: 'POST',
          data: {filename: file.filename, data: file.data},
          success: function(data, status, xhr) {}
    });      
  });

在服务器端,您会收到base64编码的值,可以轻松将其转换为二进制值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM