Java Spring boot 上传表单数据和文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51938056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:18:34  来源:igfitidea点击:

Spring boot upload form data and file

javaspring-bootspring-securitymultipartform-data

提问by Lazaruss

I am making a spring boot REST application. I am trying to make a multipart form upload controller which will handle a form data and a file upload together. This is my controller code at the moment :

我正在制作一个 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);
    }

I have tried both with the @ModelAttribute annotation and sending request parameters, but both of these methods have failed.

我已经尝试过 @ModelAttribute 注释和发送请求参数,但这两种方法都失败了。

This is the request i am sending :

这是我发送的请求:

---------------------------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”

string_value_1
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_2”

string_value_2
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_3”

string_value_3
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_4”

string_value_4
---------------------------acebdf13572468
Content-Disposition: form-data; name=”param_name_5”

string_value_5
---------------------------acebdf13572468--

My application is stateless, and uses spring security with authorities. In my security package, i have included the AbstractSecurityWebApplicationInitializer class

我的应用程序是无状态的,并与权威一起使用 spring 安全性。在我的安全包中,我包含了 AbstractSecurityWebApplicationInitializer 类

public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
            insertFilters(servletContext, new MultipartFilter());
        }
    }

I also use a StandardServletMultipartResolver in my @Configuration class

我还在 @Configuration 类中使用了 StandardServletMultipartResolver

And in my WebInitializer, i add this code :

在我的 WebInitializer 中,我添加了以下代码:

MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp", 
                3 * 1024 * 1024, 6 * 1024 * 1024, 1 * 512 * 1024);        
apiSR.setMultipartConfig(multipartConfigElement);

When i try to use the controller with the commented code (@RequestParams annotations), i get a 404 not found error. And when i try to use the controller with the @ModuleAttribute annotation, the model object is empty.

当我尝试使用带有注释代码(@RequestParams 注释)的控制器时,出现 404 not found 错误。当我尝试使用带有 @ModuleAttribute 注释的控制器时,模型对象为空。

采纳答案by Moler

I had a similar problem. When you want to send Object+ Multipart. You have to (or at least I don't know other solution) make your controller like that:

我有一个类似的问题。当您想发送Object+ 时Multipart。你必须(或者至少我不知道其他解决方案)让你的控制器像这样:

public void createNewObjectWithImage(@RequestParam("model") String model, @RequestParam(value = "file", required = false) MultipartFile file)

And then: Convert String to your Object using:

然后:使用以下方法将字符串转换为您的对象:

ObjectMapper mapper = new ObjectMapper();
ModelDTO modelDTO = mapper.readValue(model, ModelDTO.class);

And in Postman you can send it like that: enter image description here

在 Postman 中,您可以这样发送: 在此处输入图片说明

回答by ygModesto

can receive objects and files

可以接收对象和文件

@PostMapping(value = "/v1/catalog/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
public void createNewObjectWithImage(
         @RequestPart ModelTO modelTO,
         @RequestPart MultipartFile image)

ModelTO

模型TO

public class ModelTO {

    private String name;


    public ModelTO() {
        super();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

and curl example:

和卷曲示例:

curl -X POST "https://your-url.com/v1/catalog/create" -H  "accept: application/json;charset=UTF-8" -H  "Content-Type: multipart/form-data" -F "image=@/pathtoimage/powerRager.jpg;type=image/jpeg" -F "modelTO={\"name\":\"White\"};type=application/json;charset=utf-8"

Postman and other software not support send application/json type for form-data params.

邮递员和其他软件不支持表单数据参数的发送应用程序/json 类型。