SpringRESTTemplate上载二进制文件

nx7onnlm  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(494)

[在此处输入图像描述][1][1]:https://i.stack.imgur.com/kfemq.png
我想编写一个客户端代码来使用api。api需要一个文本文件。当我在 Postman 工具中选择二进制文件选项并从本地文件中选择任何文本文件时,它起作用了。如何在Spring实现这一点?。我尝试了多部分表单数据,但没有成功。

ekqde3dh

ekqde3dh1#

如果你是说文件

  1. @RestController
  2. public class FileContentController {
  3. @RequestMapping(value="/up", method = RequestMethod.POST)
  4. public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file)
  5. throws IOException {
  6. String contentType=file.getContentType());
  7. InputStream i=file.getInputStream();
  8. return new ResponseEntity<>(HttpStatus.OK);
  9. }
  10. return null;
  11. }

此外,spring boot具有多部件配置,您应该启用它并设置大小和tempdir,在早期版本中,spring boot需要添加:

  1. spring.servlet.multipart.max-file-size=128KB
  2. spring.servlet.multipart.max-request-size=128KB
  3. spring.servlet.multipart.enabled=true
  4. spring.servlet.multipart.location=${java.io.tmpdir}

然而,在客户端代码中,您不应该在头post请求中设置内容类型application/json,简单获取应该是这样的

  1. const input = document.getElementById('uploadInput');
  2. const data = new FormData();
  3. data.append('file', input.files[0]);
  4. var resp = await fetch('upload/', {
  5. method: 'POST',
  6. body: data
  7. });
  8. if (!resp.ok) {
  9. throw new Error(`HTTP error! status: ${resp.status}`);
  10. }
  11. if (resp.ok) {
  12. await this.images();
  13. }
展开查看全部
x4shl7ld

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);

相关问题