Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot upload form data and file

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.

like image 439
Lazaruss Avatar asked Aug 20 '18 20:08

Lazaruss


2 Answers

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

like image 96
Moler Avatar answered Nov 16 '22 13:11

Moler


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

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.

like image 21
ygModesto Avatar answered Nov 16 '22 12:11

ygModesto