Angular - 文件上传请求,添加@RequestParam

时间:2016-11-10 14:32:21

标签: angularjs spring http spring-mvc

我想将@RequestParam添加到我的http请求中,以便它与spring MVC @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

}

1 个答案:

答案 0 :(得分:2)

所以我只是将另一个参数添加到我的FormData

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

匹配@RequestParam

感谢。