我正在制作一个 Spring Boot REST 应用程序。我正在尝试制作一个多部分表单上传控制器,它将一起处理表单数据和文件上传。这是我目前的控制器代码: @RequestMapping(value = "", method = RequestMethod.POST, headers="Content-Type=multipart/form-data") @PreAuthorize("hasRole('ROLE_MODERATOR')") @ResponseStatus(HttpStatus.CREATED) public void createNewObjectWithImage( /*@RequestParam(value="file", required=true) MultipartFile file, @RequestParam(value="param_name_1", required=true) final String param_name_1, @RequestParam(value="param_name_2", required=true) final String param_name_2, @RequestParam(value="param_name_3", required=true) final String param_name_3, @RequestParam(value="param_name_4", required=true) final String param_name_4, @RequestParam(value="param_name_5", required=true) final String param_name_5*/ @ModelAttribute ModelDTO model, BindingResult result) throws MyRestPreconditionsException { //ModelDTO model = new ModelDTO(param_name_1, param_name_2, param_name_3, param_name_4, param_name_5); modelValidator.validate(model, result); if(result.hasErrors()){ MyRestPreconditionsException ex = new MyRestPreconditionsException( "Model creation error", "Some of the elements in the request are missing or invalid"); ex.getErrors().addAll( result.getFieldErrors().stream().map(f -> f.getField()+" - "+f.getDefaultMessage()).collect(Collectors.toList())); throw ex; }// at the moment, model has a MultipartFile property //model.setImage(file); modelServiceImpl.addNew(model); }我已经尝试过 @ModelAttribute 注释和发送请求参数,但这两种方法都失败了。这是我发送的请求:---------------------------acebdf13572468Content-Disposition: form-data; name="file"; filename="mint.jpg"Content-Type: image/jpeg<@INCLUDE *C:\Users\Lazaruss\Desktop\mint.jpg*@>---------------------------acebdf13572468Content-Disposition: form-data; name=”param_name_1”
2 回答
大话西游666
TA贡献1817条经验 获得超14个赞
我有一个类似的问题。当您想发送Object
+ 时Multipart
。你必须(或者至少我不知道其他解决方案)让你的控制器像这样:
public void createNewObjectWithImage(@RequestParam("model") String model, @RequestParam(value = "file", required = false) MultipartFile file)
然后:使用以下方法将字符串转换为您的对象:
ObjectMapper mapper = new ObjectMapper(); ModelDTO modelDTO = mapper.readValue(model, ModelDTO.class);
在 Postman 中,您可以这样发送:
添加回答
举报
0/150
提交
取消