Spring Boot实现Postman文件上传请求遇500错误求助
问题原因
你当前的代码直接将文件字节以APPLICATION_OCTET_STREAM格式发送,而目标API要求的是multipart/form-data类型的表单请求,且必须包含名为file的表单字段。这就是API返回"文件大小为0k"的核心原因——它找不到预期的file字段。
解决方案
修改代码,构建符合要求的multipart表单请求:
public String uploadPdf(MultipartFile attachment) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + getAccessToken()); // 设置请求内容类型为multipart/form-data headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 构建multipart表单数据,键名必须为"file" MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); // 将MultipartFile包装为ByteArrayResource,指定原文件名模拟OkHttp的表单提交行为 body.add("file", new ByteArrayResource(attachment.getBytes()) { @Override public String getFilename() { return attachment.getOriginalFilename(); } }); URI uri = URI.create("https://api/attachment"); RestTemplate template = new RestTemplate(); try { HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); ResponseEntity<String> response = template.exchange(uri, HttpMethod.POST, requestEntity, String.class); return response.getBody(); } catch (Exception e) { e.printStackTrace(); return "Impossible to send document"; } }
关键说明
- 必须用
MultiValueMap封装表单数据,确保键名严格为file,和Postman/OkHttp代码中的字段名一致。 - 使用
ByteArrayResource包装文件字节并指定文件名,还原OkHttp中addFormDataPart的提交逻辑。 - 请求头的
ContentType必须设置为MULTIPART_FORM_DATA,不能使用APPLICATION_OCTET_STREAM。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

