2015-04-21 105 views
0

我需要用ajax從客戶端上傳文件到服務器端。我已經讀過,這是可能的,但在我的項目中不起作用。我正在與Jquery和Spring Portlet合作。用ajax和spring portlet從客戶端上傳文件到服務器端

這是我在客戶端代碼:

<form method="post" id="formUploadFile"> 
    <input id="uprloadFile" type="file" name="file"/> 
    <input id="submitButton" type="button" value="Upload File" /> 
</form> 

的javascript:

var dataFormulario = new FormData($('#formUploadFile')[0]); 

$.ajax({ 
    url : accredit.cargarDocumentoURL, 
    type : "POST", 
    data : dataFormulario, 
    cache: false, 
    contentType: false, 
    processData: false, 
    success : function(data) { 
     alert("Success"); 
    }, 
    error : function(data) { 
     alert("Error"); 
    } 
}); 

我得到了我的控制器的這種方法的文件:

@ResourceMapping("uploadFile") 
public void uploadFile(ResourceResponse response, 
     @ModelAttribute(value = "AccreditCommand") AccreditCommand accreditCommand) { 
    System.out.println("File : " + accreditCommand.getFile()); 
    successResponse(response); 
} 

我對象的ModelAttribute :

public class AccreditCommand { 

    private byte[] file; 

    public byte[] getFile() { 
     return file; 
    } 

    public void setFile(byte[] file) { 
     this.file = file; 
    } 

} 

日誌中沒有錯誤,並且AccreditCommand中的字段「文件」爲空。

當我檢查谷歌瀏覽器的網絡選項卡,它顯示了在請求負載:

------ WebKitFormBoundarymChhAWgmzsVyaJ2P 內容處置:表格數據; NAME = 「文件」;文件名= 「Cargo_AC123TU2015991946296415.pdf」 內容類型:應用程序/ PDF

------ WebKitFormBoundarymChhAWgmzsVyaJ2P--

看來,我送一個空文件。我不知道我做錯了什麼。

+0

請參考以下鏈接http://hmkcode.com/spring-mvc-upload-file-ajax-jquery-formdata/ – Dev

回答

1

下面是如何我一直在使用AJAX

JS

<script> 
function uploadFormDataUsingAjax(){ 
    var uploadForm = new FormData(); 
    uploadForm.append("file", file2.files[0]); 
    uploadForm.append("name", document.getElementById('fileName').value); 
    $.ajax({ 
    url: 'http://localhost:8080/yourProjectName/uploadFile', 
    data: uploadForm, 
    dataType: 'text', 
    processData: false, 
    contentType: false, 
    type: 'POST', 
    success: function(data){ 
    console.log(data); 
    } 
    }); 
} 
</script> 

的Html

<form id="uploadFileForm" method="post" action="uploadFile" enctype="multipart/form-data"> 
    <!-- File input -->  
    AjaxFileToUpload<input name="file" id="file2" type="file" /><br/> 
    Name: <input type="text" id="fileName" name="name"><br /> 
</form> 
<button value="Submit" onclick="uploadFormDataUsingAjax()" >UploadFile</button> 

控制器

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 
private @ResponseBody 
String uploadFileHandler(@RequestParam("name") String name, 
     @RequestParam("file") MultipartFile file) { 
    if (!file.isEmpty()) { 
     try { 
      byte[] bytes = file.getBytes(); 

      // Creating the directory to store file 
      String rootPath = "path To save your file/Spring_Upload"; 
      File dir = new File(rootPath + File.separator + "tmpFiles"); 
      if (!dir.exists()) 
       dir.mkdirs(); 

      // Create the file on server 
      File serverFile = new File(dir.getAbsolutePath() 
        + File.separator + name); 
      BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(serverFile)); 
      stream.write(bytes); 
      stream.close(); 

      logger.info("Server File Location=" 
        + serverFile.getAbsolutePath()); 

      return "You successfully uploaded file=" + name; 
     } catch (Exception e) { 
      return "You failed to upload " + name + " => " + e.getMessage(); 
     } 
    } else { 
     return "You failed to upload " + name 
       + " because the file was empty."; 
    } 
} 

希望這將幫助您成功上傳文件到服務器

感謝

+0

開發嗨,我用你的JS和HTML我,因爲我控制器使用Spring Portlet(不是Spring MVC),我不能使用@ResponseBody,但它不起作用(文件到達空)。你有沒有使用Spring Portlet的例子? – Walter

相關問題