@PostMapping("/upload")
public ReResultVo upload(@RequestParam(“file”) MultipartFile multipartFile, HttpServletRequest request) {
if (multipartFile == null) {
return new ReResultVo(false, “文件为空!”);
}
/* String result = null;
try {
//ApplicationHome home = new ApplicationHome(this.getClass());
//String dirRoot = home.getSource().getParentFile().getParent();
//String dirFile = String.format("%s/%s", “D:/static/upload/”);
File dest = new File(“D:/static/upload/”, Timestamp.valueOf(LocalDateTime.now()).getTime() + “-” + multipartFile.getOriginalFilename());
dest.getParentFile().mkdirs();
multipartFile.transferTo(dest);
result = dest.getPath();
} catch (IOException e) {
return new ReResultVo(false, “文件上传失败!”);
}
return new ReResultVo(true, “上传成功!”, result);/
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String logoPathDir = “/suggest/upload/” + new Date(Timestamp.valueOf(LocalDateTime.now()).getTime());
/** 得到文件保存目录的真实路径 /
String logoRealPathDir = multipartRequest.getSession().getServletContext().getRealPath(logoPathDir);
/* 根据真实路径创建目录* /
File logoSaveFile = new File(logoRealPathDir);
if (!logoSaveFile.exists()) {
logoSaveFile.mkdirs();
}
/* 获取文件的后缀* /
String suffix = multipartFile.getOriginalFilename().substring(
multipartFile.getOriginalFilename().lastIndexOf("."));
/* 使用UUID生成文件名称* /
String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
/* 拼成完整的文件保存路径加文件* /
String fileName = logoRealPathDir + File.separator + logImageName;
File file = new File(fileName);
try {
multipartFile.transferTo(file);
} catch (IllegalStateException e) {
return new ReResultVo(false, “文件上传失败!”);
} catch (IOException e) {
return new ReResultVo(false, “文件上传失败!”);
}
/* 打印出上传到服务器的文件的绝对路径* /
System.out.println("***************" + fileName + “**************”);
return new ReResultVo(true, “上传成功!”, fileName);
}
@GetMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam String filePath) {
byte[] body = null;
try {
String parentPath = “D:/static/upload/”;
File file = new File(parentPath + filePath);
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add(“Content-Disposition”, “attchement;filename=” + “parentPath” + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers, statusCode);
return entity;
} catch (Exception e) {
this.logger.error(e.toString());
}
return new ResponseEntity<>(body, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}