Spring不支持内容类型'multipart / form-data; boundary = ---- WebKitFormBoundary ...'

时间:2018-07-14 10:17:19

标签: spring rest spring-mvc

春季5.0.7:MVC,数据,安全性。 我配置了multipartResolver

我发送下一个Ajax请求:

$.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.');
});

但是有一个错误:Content type 'multipart/form-data;boundary=----WebKitFormBoundary6xBCDjCtYYuUVR5c' not supported

为什么?我不明白为什么会发生错误。

控制器:

@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;
    }
}

我不知道还要写些什么,但是SO需要更多文本。 (

2 个答案:

答案 0 :(得分:3)

在您的控制器中,使用@RequestParam代替@RequestBody。

遇到同样的问题,它对我有用。 有关更多信息,请参见此SO answer

答案 1 :(得分:1)

您需要添加此Maven依赖项commons-fileupload:commons-fileupload:1.3.x 并声明MultipartResolver bean

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

以上方法适用于Spring控制器。如果要对异步Spring控制器进行操作,请参阅本文。 http://www.baeldung.com/spring-file-upload

希望有帮助!