【发布时间】:2018-01-22 19:14:48
【问题描述】:
我正在将一个 formData 对象传递给我的 Spring 后端:
imageBanner(banner: File, bannerPath: string, id: number, callback: (response) => void){
var formData = new FormData();
formData.append('name', banner.name);
console.log(formData.get('name'));
formData.append('file', banner);
console.log(formData.get('file'));
this.sendPost("/upload/" + bannerPath, formData, response => {
callback(response);
});
}
控制台日志显示:
1.jpg
File {name: "1.jpg", lastModified: 1496737372408, lastModifiedDate: Tue Jun 06 2017 10:22:52 GMT+0200 (W. Europe Daylight Time), webkitRelativePath: "", size: 38983…}
所以看起来 formData 有一些值。
在后端我有这个:
@RequestMapping(value="/rest/upload/localeventbanner", method=RequestMethod.POST, headers = "content-type!=multipart/form-data")
public @ResponseBody String uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
log("success");
return "You successfully uploaded file=" + name;
} catch (Exception e) {
log("fail");
return "You failed to upload";
}
} else {
log("nope");
return "You failed to upload " + name
+ " because the file was empty.";
}
}
我在控制台中得到的回报是:
"{"timestamp":1502745177167,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"必需的字符串参数'name' 不存在","path":"/beheerback/rest/upload/localeventbanner"}"
它说名称不存在,但是当我在前端记录它时,它显示名称存在于 formData 对象中。
【问题讨论】: