描述:
? ? ? ? 新需求,公司需要将一体机的多张图片通过java后端上传到远程服务器的后台管理系统。
客户端实现
@GetMapping("uploadImg")
public static String uploadImg(){
// 读取图片
String imageLocation1 = "D:\\1.png";
String imageLocation2 = "D:\\2.png";
String imageLocation3 = "D:\\3.png";
FileSystemResource fileSystemResource1 = new FileSystemResource(imageLocation1);
FileSystemResource fileSystemResource2 = new FileSystemResource(imageLocation2);
FileSystemResource fileSystemResource3 = new FileSystemResource(imageLocation3);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", fileSystemResource1);
form.add("file", fileSystemResource2);
form.add("file", fileSystemResource3);
// 上传图片 YmlValueConfig.getHttpUrl():第三方服务器地址
String url = YmlValueConfig.getHttpUrl() + "/file/uploadFile";
String res = RestTemplateUtils.httpUploadImg(url, form);
log.info(res);
return res;
}
?服务器接口
//上传文件
@PostMapping("/file/uploadFile")
@ResponseBody
public Result uploadFile(@RequestParam("file") MultipartFile[] fileList ) {
log.info("fileList:[{}]", fileList);
String filePathName = null;
try {
File dir = new File(imagePath);
if (!dir.exists()) {
dir.mkdirs();
dir.setWritable(true, false);
}
for (MultipartFile mfile : fileList) {
String fileName = mfile.getOriginalFilename();
filePathName = imagePath + fileName;
FileCopyUtils.copy(mfile.getBytes(), new File(filePathName));
}
} catch (IOException e) {
log.error("upload error:[{}]", e.getMessage());
return Result.success(HttpStatus.ERROR, "上传失败");
}
return Result.success(HttpStatus.SUCCESS, "上传成功");
}
简单实现,仅供参考
|