2016-11-10 64 views
0

我想添加@RequestParam到我的http請求,所以它會匹配spring MVC @RequestParamAngular - 文件上傳請求,添加@RequestParam

如何添加這對我的文件上傳請求:

/* 
@param file - file from input 

@param uploadUrl - url 
*/  

    this.uploadFileToUrl = function(file, uploadUrl){ 
       var fd = new FormData(); 
       //add file to FormData 
       fd.append(file.name, file); 
       //send request 
       $http.post(uploadUrl, fd, { 
        transformRequest: angular.identity, 
        headers: {'Content-Type': undefined} 
       }) 
       .success(function(result){ 
        console.log(result); 
       }) 
       .error(function(err){ 
        console.log(err); 
       }); 
      } 

在我的後端錯誤是Required String parameter 'filename' is not present 這裏是我的Spring MVC controller(只有頭部分):

@Controller 
@RequestMapping("/file") 
public class FileUploadController { 
    /** 
    * Upload single file using Spring Controller 
    */ 
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 
    public @ResponseBody String uploadFileHandler(@RequestParam("filename") String filename, @RequestParam("file") MultipartFile file) { 
//rest of the function 

}

+0

我認爲你已經諮詢了Angular'$ http'或'FormData'的文檔,並試圖按照描述添加參數。你遇到過什麼問題? – zeroflagL

+0

後臺錯誤 - 必需的字符串參數'文件名'不存在,錯誤代碼400 –

+0

沒關係,我想出了自己,發佈了答案。 –

回答

2

所以我只是追加了另一個參數給我的FormData

fd.append('file', file); 
fd.append('filename', file.name); 

匹配@RequestParam的。

謝謝。