2013-10-02 53 views
2

我想從我的客戶端(jQuery)發佈二進制文件到我的服務器(Java)。我正在使用Apache CXF和REST。該文件正在將其傳送到服務器,並立即引發異常。如何使用REST發佈二進制文件從JQuery客戶端到Java服務器使用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

您要發送的文件後的身體,你需要做的是以多部分形式的數據主體發送文件。您可以使用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'); 
     } 
    }); 
    } 
+0

這固定了客戶端。下面我的答案是我的服務器端解決方案。 –

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; 
    } 
} 
相關問題