如何使用REST将二进制文件从JQuery Client发布到Java Server

时间:2013-10-02 22:47:31

标签: java jquery rest post binary

我正在尝试将二进制文件从我的客户端(jQuery)发布到我的服务器(Java)。我正在使用Apache CXF和REST。该文件正在向服务器发送,该服务器会立即抛出异常。

这是客户端的JavaScript:

  function handleFileUpload() {
     console.log("handleFileUpload called");
     var url = "http://myserver:8181/bootstrap/rest/upload/license";
     var file = $('#file_upload').get(0).files[0];
     $.ajax({
        url: url,
        type: "post",
        data: file,
        processData: false,
        success: function(){
           $("#file_upload_result").html('submitted successfully');
        },
        error:function(){
          $("#file_upload_result").html('there was an error while submitting');
        }   
    }); 
  }

这是服务器端代码:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("/license")
public String uploadLicenseFile(@FormParam("file") InputStream pdfStream) 
{
    try 
    {
        //byte[] pdfByteArray = convertInputStreamToByteArrary(pdfStream);
        //fileLength = pdfByteArray.length;
        fileLength = pdfStream.available();
        response = "Upload successful!";
        // TODO read file and store params in memory
    } 
    catch (Exception ex) 
    {
        response = "Upload failed: " + ex.getMessage();
        fileLength = 0;
    }
    return getFileLength();
}

2 个答案:

答案 0 :(得分:5)

您要将文件作为帖子正文发送,您要做的是将文件发送到多部分表单数据正文中。您可以使用FormData对象执行此操作。

  function handleFileUpload() {
     console.log("handleFileUpload called");
     var url = "http://myserver:8181/bootstrap/rest/upload/license";
     var file = $('#file_upload').get(0).files[0];
     var formData = new FormData();
     formData.append('file', file)
     $.ajax({
        url: url,
        type: "post",
        data: formData,
        processData: false,
        contentType: false,
        success: function(){
           $("#file_upload_result").html('submitted successfully');
        },
        error:function(){
          $("#file_upload_result").html('there was an error while submitting');
        }   
    }); 
  }

答案 1 :(得分:1)

这是我与Musa客户端解决方案合作的服务器端代码。

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/license")
public void uploadLicenseFile(MultipartBody body) 
{
    try 
    {
        List<Attachment> all = body.getAllAttachments();
        Attachment a = all.get(0);
        InputStream is = a.getDataHandler().getInputStream();
        //byte[] pdfByteArray = convertInputStreamToByteArrary(pdfStream);
        //fileLength = pdfByteArray.length;
        fileLength = is.available();
        response = "Upload successful!";
        // TODO read file and store params in memory
    } 
    catch (Exception ex) 
    {
        response = "Upload failed: " + ex.getMessage();
        fileLength = 0;
    }
}