@GetMapping("/upload")
public String upload() throws Exception{
// 指定上传路径
String url = "http://xxx:xxx/upload";
// 指定类型为multipart/form-data
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data");
headers.setContentType(type);
// 封装参数
MultiValueMap form = new LinkedMultiValueMap<>();
String source = "本地路径";
FileInputStream fileInputStream = new FileInputStream(new File(source));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int length = 0;
byte[] b = new byte[1024];
while ((length = fileInputStream.read(b)) != -1) {
bos.write(b, 0, length);
}
// 生成byte[] 测试上传流
byte[] bytes = bos.toByteArray();
// 上传本地文件
FileSystemResource fileSystemResource = new FileSystemResource("本地文件路径");
// 上传byte[]
ByteArrayResource byteArrayResource = new ByteArrayResource(bytes) {
@Override
public String getFilename() {
return "xxx.txt";
}
};
form.add("file", byteArrayResource);
form.add("filename", "xxx.txt");
HttpEntity files = new HttpEntity(form, headers);
return restTemplate.postForObject(url, files, String.class);
}
在java中使用restTemplate上传文件
最新推荐文章于 2024-07-16 10:54:04 发布