【发布时间】:2021-09-18 09:40:35
【问题描述】:
我想编写一个客户端代码来使用一个 API。 API 需要一个文本文件。当我在邮递员工具中选择二进制文件选项并从本地选择任何文本文件时,它就起作用了。如何在春季实施?我试过 MULTIPART_FORM_DATA 但没有运气。
【问题讨论】:
-
展示你的努力
标签: java spring spring-boot resttemplate
我想编写一个客户端代码来使用一个 API。 API 需要一个文本文件。当我在邮递员工具中选择二进制文件选项并从本地选择任何文本文件时,它就起作用了。如何在春季实施?我试过 MULTIPART_FORM_DATA 但没有运气。
【问题讨论】:
标签: java spring spring-boot resttemplate
如果你的意思是文件
@RestController
public class FileContentController {
@RequestMapping(value="/up", method = RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file)
throws IOException {
String contentType=file.getContentType());
InputStream i=file.getInputStream();
return new ResponseEntity<>(HttpStatus.OK);
}
return null;
}
spring boot 也有多部分配置,你应该启用它并设置 size 和 tempdir ,在早期版本的spring boot中需要添加:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}
但是,在您的客户端代码中,您不应在标头发布请求中设置内容类型 application/json 简单的fetch应该是这样的
const input = document.getElementById('uploadInput');
const data = new FormData();
data.append('file', input.files[0]);
var resp = await fetch('upload/', {
method: 'POST',
body: data
});
if (!resp.ok) {
throw new Error(`HTTP error! status: ${resp.status}`);
}
if (resp.ok) {
await this.images();
}
【讨论】: