[在此处输入图像描述][1][1]:https://i.stack.imgur.com/kfemq.png我想编写一个客户端代码来使用api。api需要一个文本文件。当我在 Postman 工具中选择二进制文件选项并从本地文件中选择任何文本文件时,它起作用了。如何在Spring实现这一点?。我尝试了多部分表单数据,但没有成功。
ekqde3dh1#
如果你是说文件
@RestControllerpublic 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;}
@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具有多部件配置,您应该启用它并设置大小和tempdir,在早期版本中,spring boot需要添加:
spring.servlet.multipart.max-file-size=128KBspring.servlet.multipart.max-request-size=128KBspring.servlet.multipart.enabled=truespring.servlet.multipart.location=${java.io.tmpdir}
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}
然而,在客户端代码中,您不应该在头post请求中设置内容类型application/json,简单获取应该是这样的
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();}
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();
x4shl7ld2#
我设法找到了解决方案,它成功了,这是我的代码。阿里,谢谢你的帮助。解决办法很简单。inputstream in=new fileinputstream(“d:\uploadfiles\test.json”);httpentity<byte[]>entity=新的httpentity<>(org.apache.commons.io.ioutils.tobytearray(in),头文件);responseentity response=resttemplate.exchange(uploadurldtls.getuploadurl(),httpmethod.put,entity,string.class);
2条答案
按热度按时间ekqde3dh1#
如果你是说文件
此外,spring boot具有多部件配置,您应该启用它并设置大小和tempdir,在早期版本中,spring boot需要添加:
然而,在客户端代码中,您不应该在头post请求中设置内容类型application/json,简单获取应该是这样的
x4shl7ld2#
我设法找到了解决方案,它成功了,这是我的代码。阿里,谢谢你的帮助。解决办法很简单。
inputstream in=new fileinputstream(“d:\uploadfiles\test.json”);
httpentity<byte[]>entity=新的httpentity<>(org.apache.commons.io.ioutils.tobytearray(in),头文件);
responseentity response=resttemplate.exchange(uploadurldtls.getuploadurl(),httpmethod.put,entity,string.class);