猿问

Spring boot 上传表单数据和文件

我正在制作一个 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 注释和发送请求参数,但这两种方法都失败了。


这是我发送的请求:


---------------------------acebdf13572468

Content-Disposition: form-data; name="file"; filename="mint.jpg"

Content-Type: image/jpeg


<@INCLUDE *C:\Users\Lazaruss\Desktop\mint.jpg*@>

---------------------------acebdf13572468

Content-Disposition: form-data; name=”param_name_1”


慕码人2483693
浏览 272回答 2
2回答

大话西游666

我有一个类似的问题。当您想发送Object+ 时Multipart。你必须(或者至少我不知道其他解决方案)让你的控制器像这样:public&nbsp;void&nbsp;createNewObjectWithImage(@RequestParam("model")&nbsp;String&nbsp;model,&nbsp;@RequestParam(value&nbsp;=&nbsp;"file",&nbsp;required&nbsp;=&nbsp;false)&nbsp;MultipartFile&nbsp;file)然后:使用以下方法将字符串转换为您的对象:ObjectMapper&nbsp;mapper&nbsp;=&nbsp;new&nbsp;ObjectMapper(); ModelDTO&nbsp;modelDTO&nbsp;=&nbsp;mapper.readValue(model,&nbsp;ModelDTO.class);在 Postman 中,您可以这样发送:
随时随地看视频慕课网APP

相关分类

Java
我要回答