在开始提问之前,英语不准确,因为我是韩国人。
我使用Spring Boot 1.5.14。
我正在使用FormData实现文件上传,并且发生了400错误。
1。 Javascript
var formData = new FormData();
formData.append('autoSelect', 'autoSelect');
formData.append('file', fileObj);
$.ajax({
url: '/api/portfolios/' + pofolNo + '/main-image',
type: 'PUT',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: formData,
async: false,
});
2。 Spring Controller(无效)
@PutMapping("{pofolNo}/main-image")
public CommonApiResponse changePortfolioMainImage(
@PathVariable("pofolNo") Integer pofolNo,
@RequestParam("autoSelect") String autoSelect,
@RequestParam("mainImage") MultipartFile mainImage) {
log.debug("check : {} / {} / {}", pofolNo, autoSelect, mainImage);
return ok(null);
}
上面的代码导致显示400错误,表明autoSelect参数不存在。
所以我这样检查HttpServletRequest.getParameter("autoSelect")
。
3。 Spring Controller(工作)
@PutMapping("{pofolNo}/main-image")
public CommonApiResponse changePortfolioMainImage(
@PathVariable("pofolNo") Integer pofolNo,
HttpServletRequest request,
@RequestParam("mainImage") MultipartFile mainImage) {
log.debug("check : {} / {} / {}", pofolNo, request.getParameter("autoSelect"), mainImage);
return ok(null);
}
以上代码结果成功。
有什么区别?我无法理解@RequestParam
并没有与HttpServletRequest
一起工作。
答案 0 :(得分:1)
第二个无效,因为@RequestParam(“ autoSelect”)字符串不需要为null。
除非您必须提供默认值或require = false
第三个始终有效,因为它仅注入HttpServletRequest。但请注意,该值可能仍为null。
如何在multipart / form-data中获取参数值并取决于您的servlet API版本完全不同。
关于multipart和servlet api版本的更清楚的解释: