Spring RestTemplate 上传二进制文件

问题描述

Image

我想编写一个客户端代码来使用 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 entity = new HttpEntity(org.apache.commons.io.IOUtils.toByteArray(in),headers);

ResponseEntity response = restTemplate.exchange(uploadURLDtls.getUploadUrl(),HttpMethod.PUT,实体,String.class);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...