Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content type 'multipart/form-data;boundary=----WebKitFormBoundary...' not supported Spring

Spring 5.0.7: MVC, Data, Security. I configure multipartResolver.

I send next Ajax request:

$.ajax({
    type: 'POST',
    cache: false,
    processData: false,
    contentType: false,
    url: '/api/v1/category/add',
    data: new FormData(form)
}).done(result=>{console.log(result);}).fail(result=>{
    console.error('ERROR:', result.responseJSON.httpStatus, result.responseJSON.message, result);
    self.toast.error('API Error.');
});

But there is an error: Content type 'multipart/form-data;boundary=----WebKitFormBoundary6xBCDjCtYYuUVR5c' not supported

why? i don't understand why error happen.

Controller:

@RestController
@Secured("hasRole('ADMIN')")
@RequestMapping(value = "/api/v1")
public class ApiController {

    private static final Logger LOGGER = LogManager.getLogger(ApiController.class);

    @PostMapping(value = "/category/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    private Response categoryAdd(Response response, @RequestBody CategoryAddForm categoryAddForm) {
        LOGGER.info(categoryAddForm.toString());
        return response;
    }

}

CategoryAddForm:

public class CategoryAddForm {

    private String name;

    private String description;

    private MultipartFile preview;

    public CategoryAddForm() { }

    public CategoryAddForm(String name, String description, MultipartFile preview) {
        this.name = name;
        this.description = description;
        this.preview = preview;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public MultipartFile getPreview() {
        return preview;
    }
}

I do not know what else to write, but SO requires more text. (

like image 360
Tsyklop Avatar asked Jul 14 '18 10:07

Tsyklop


2 Answers

In your controller, use @RequestParam instead of @RequestBody.

Was having the same issue and it worked for me. See this SO answer for more info

like image 196
Seun Matt Avatar answered Oct 01 '22 15:10

Seun Matt


You need to add this maven dependency commons-fileupload:commons-fileupload:1.3.x and declare MultipartResolver bean

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);
    return multipartResolver;
}

Above method is for Spring controllers. If you want to do for Async Spring controllers refer this article. http://www.baeldung.com/spring-file-upload

Hope it helps!

like image 44
Archit Avatar answered Oct 01 '22 15:10

Archit