3

クライアント (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();
}
4

2 に答える 2

6

投稿本文としてファイルを送信しています。やりたいことは、ファイルをマルチパートフォームのデータ本文で送信することです。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');
        }   
    }); 
  }
于 2013-10-02T22:52:13.107 に答える