调用接收Multipart文件的REST API时抛出HttpMediaTypeNotSupportedException
问题分析与解决方案
先纠正API接口的拼写错误
你提供的接口代码里,consumes参数存在拼写错误:MediaType.MULTIPART_FORM_DATE_VALUE应该改为MediaType.MULTIPART_FORM_DATA_VALUE,这个错误会导致接口无法正确识别multipart请求,先修正这个问题:
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<String> upload(@RequestPart("file") MultipartFile file, @RequestParam("path") String path) { // 业务逻辑 }
调用代码的核心错误
你的调用代码有两个致命问题,直接引发HttpMediaTypeNotSupportedException:
- 错误将文件放到URL查询参数中:Multipart文件必须放在请求体的多部分内容里,而非URL的query参数,这种错误写法会让请求被默认识别为
application/x-www-form-urlencoded类型,和接口要求的multipart/form-data不匹配。 - 请求体为空:你构建的
HttpEntity没有携带任何请求内容,服务器无法识别这是一个文件上传请求。
修正后的调用代码
public void uploadFile() { Path path = Paths.get("C:/ABC.txt"); byte[] content = null; try { content = Files.readAllBytes(path); } catch (final IOException e) { e.printStackTrace(); // 不要忽略异常,便于排查问题 } // 构建符合要求的MultipartFile,第一个参数要和接口@RequestPart的name一致:"file" MultipartFile file = new MockMultipartFile("file", "ABC.txt", MediaType.TEXT_PLAIN_VALUE, content); // 构建multipart请求体,用MultiValueMap存储多部分内容 MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); // 用ByteArrayResource包装文件字节,RestTemplate需要这个类型识别文件部分 requestBody.add("file", new ByteArrayResource(file.getBytes()) { @Override public String getFilename() { return file.getOriginalFilename(); // 必须返回文件名,否则接口无法正确解析 } }); // 设置请求头,明确指定内容类型为multipart/form-data HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 构建包含请求体和头的HttpEntity HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers); // 构建请求URL,path参数作为query参数传递(符合接口@RequestParam的定义) UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(oauthURL + "/uploadFile"); urlBuilder.queryParam("path", "/temp"); try { ResponseEntity<String> response = restTemplate.exchange( urlBuilder.build().encode().toUri(), HttpMethod.POST, requestEntity, String.class ); // 这里可添加响应处理逻辑 } catch (Exception e) { e.printStackTrace(); } }
关键修正说明
- 请求体构建:用
MultiValueMap存储multipart内容,文件必须以ByteArrayResource(或FileSystemResource)形式放入,且需指定文件名,确保接口能正确解析MultipartFile参数。 - 请求头设置:明确设置
Content-Type为multipart/form-data,告知服务器这是多部分文件上传请求。 - 参数匹配:
MockMultipartFile的第一个参数必须和接口@RequestPart("file")的name一致,否则接口无法找到对应文件参数。 - 异常处理:不要忽略IO异常,避免文件读取失败时无法排查问题。
内容的提问来源于stack exchange,提问作者Nichole
相关产品推荐
相关产品推荐

