1。将图片上传到服务器,我是用spring的restTemplate工具类
@RequestMapping("/upload")
public Map<String, Object> uploadFile(@RequestParam("myFile") MultipartFile myFile)
throws IOException {
Map<String, Object> map = new HashMap<>();
map.put(“flag”, false);
if (myFile.isEmpty()) {
map.put(“msg”, "上传文件 不能为空!");
}
logger.info("================接收上传文件,文件名: " + myFile.getOriginalFilename());
String fileName = myFile.getOriginalFilename();
logger.info("文件保存至:{}", savePath+fileName);
File fileDir = new File(savePath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
String suffix = fileName.substring(fileName.lastIndexOf("."));
fileName = fileName.substring(0, fileName.lastIndexOf("."))+new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date())+suffix;
File file = new File(savePath+fileName);
myFile.transferTo(file);
try {
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> mapFile = new LinkedMultiValueMap<>();
mapFile.add("mfile", resource);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type","multipart/form-data");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(mapFile,headers);
ResponseEntity<String> postForEntity = restTemplate.postForEntity(uploadPath, httpEntity, String.class);
String body = postForEntity.getBody();
logger.info("上传图片返回报文:{}",body);
JSONObject respJSON = JSONObject.parseObject(body);
Integer flag = respJSON.getInteger("flag");
if(flag==1){
map.put("flag", true);
map.put("url", respJSON.getString("filePath"));
}else{
map.put("flag", false);
map.put("msg", respJSON.getString("msg"));
}
} catch (Exception e) {
logger.error("上传失败", e);
map.put("flag", false);
map.put("msg", "上传失败");
}
file.delete();
return map;
}
2.首先springmvc接收前端上传文件(单个文件)
public Map<String, Object> uploadFile(@RequestParam("myFile") MultipartFile myFile)
3.将文件临时存在服务器上,上传成功再删除,我项目中存在tomcat下
File file = new File(savePath+fileName);
myFile.transferTo(file);
4.之所以要转成File文件是因为MultipartFile不能被FileSystemResource 接收
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> mapFile = new LinkedMultiValueMap<>();
mapFile.add("mfile", resource);
5.拼装请求头和请求体(uploadPath可以是任意目的地)
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type","multipart/form-data");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(mapFile,headers);
ResponseEntity<String> postForEntity = restTemplate.postForEntity(uploadPath, httpEntity, String.class);
String body = postForEntity.getBody();
logger.info("上传图片返回报文:{}",body);
6.剩下的就是处理返回报文了