问题描述
我想编写一个客户端代码来使用 API。 API 需要一个文本文件。当我在邮递员工具中选择二进制文件选项并从我的本地选择任何文本文件时,它起作用了。如何在春季实现这一点?我尝试过 MULTIPART_FORM_DATA 但没有成功。
解决方法
如果你的意思是文件
@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 也有多个 confs,你应该启用它并设置 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 simple 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();
}
,
我设法找到了解决方案并且有效,这是我的代码。感谢阿里的帮助
InputStream in = new FileInputStream("D:\uploadFiles\test.json");
HttpEntity
ResponseEntity response = restTemplate.exchange(uploadURLDtls.getUploadUrl(),HttpMethod.PUT,实体,String.class);