Spring boot upload form data and file

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 :

    @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.

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

public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

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

I also use a StandardServletMultipartResolver in my @Configuration class

And in my WebInitializer, i add this code :

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.

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:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84313&siteId=1
Recommended