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

问题描述 投票:1回答:2

Spring 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需要更多的文字。 (

spring rest spring-mvc
2个回答
3
投票

在您的控制器中,使用@RequestParam而不是@RequestBody。

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


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控制器。如果您想为Async Spring控制器做什么,请参阅本文。 http://www.baeldung.com/spring-file-upload

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.