//文件上传
@RequestMapping(value = "saveImg", method = RequestMethod.POST)
public ModelAndView uploadImage(@RequestParam("image") MultipartFile multipartFile, HttpServletRequest request, ModelAndView model) throws Exception {
//文件上传路径
String path = request.getServletContext().getRealPath("/");
String q = path.substring(0, path.lastIndexOf("\\"));
String e = q.substring(0, q.lastIndexOf("\\"));
e += "/img";
System.out.println(path.lastIndexOf("\\"));
System.out.println(q);
System.out.println(e);
//上传文件名
String filename = multipartFile.getOriginalFilename();
File filePath = new File(e, filename);
System.out.println(path);
System.out.println(filePath.getParentFile());
System.out.println(filePath.getAbsolutePath());
//判断当前路径是否存在,如果不存在就创建一个
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件中
multipartFile.transferTo(new File(e + File.separator + filename));
//将文件名字保存在model中
model.addObject("list",filename);
model.setViewName("success");
return model;
}
//文件下载
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("name") String fileName,Model model) throws IOException {
//文件下载路径
String path = request.getServletContext().getRealPath("/");
String q = path.substring(0, path.lastIndexOf("\\"));
String e = q.substring(0, q.lastIndexOf("\\"));
e += "/img";
File file = new File(e+File.separator+fileName);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名乱码·问题
String downloadName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment",downloadName);
//application/octet-stream; 二进制流数据(最常见的文件下载)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//201 HttpStatus.CREATED
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}