【问题标题】:Upload multipart/form-data file in Spring boot and REST API在 Spring Boot 和 REST API 中上传 multipart/form-data 文件
【发布时间】:2018-06-12 12:57:01
【问题描述】:

我想上传一个 .png 文件并存储它。当我使用 content-type=multipart/form-data 发送它时,我收到了这个异常

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 
  'application/octet-stream' not supported . 

我认为我的应用程序不理解表单数据 contentType 并引发了不相关的异常。怎么了?

    @Controller
    public class ProfileController {
        private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);

        @Autowired
        ProfileService service;

        //http : http --pretty all --form PUT localhost:8080/profile/v1?thumb=glb
        @PutMapping(value = "/v1")
        public Mono<ResponseEntity<String>> upload(@RequestPart(value = "thumb", required = false) String thumbFilterName,
                                                   @RequestPart(value = "genthumb", required = false) String genthumb,
                                                   @RequestPart("hash") String hash,
                                                   @RequestPart("uploader") Long uploader,
                                                   @RequestPart("file") MultipartFile file) throws Exception {


        System.out.println(thumbFilterName);
        System.out.println(gentumb);
        System.out.println(uploader);
        System.out.println(file);
//and doing storage stuff!
return Mono.just(ResponseEntity.ok().build());
        }
    }

这是我用来发送文件的 Rest Client。注意回复。

这些是restClient的截图。使用 restClient 发送文件:

这是设置标题

【问题讨论】:

    标签: java rest spring-boot storage multipartform-data


    【解决方案1】:

    在uploader 中,您必须将@RequestPart 更改为@RequestParam

    @RequestPart("uploader") Long uploader,
    

    Javadoc explaination:

    请注意,@RequestParam 注释也可用于将“multipart/form-data”请求的部分与支持相同方法参数类型的方法参数相关联。主要区别在于,当方法参数不是 String 时,@RequestParam 依赖于通过注册的 Converter 或 PropertyEditor 进行类型转换,而 @RequestPart 依赖于 HttpMessageConverters 考虑到请求部分的“Content-Type”标头。 @RequestParam 可能与名称-值表单字段一起使用,而 @RequestPart 可能与包含更复杂内容(例如 JSON、XML)的部分一起使用。

    【讨论】:

    • 嗨,真的非常感谢您的回复,它的工作:)
    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2022-01-17
    • 2015-10-23
    相关资源
    最近更新 更多