文件上传,这里以图片上传为例(这里上传到服务器)
@RequestMapping("/upload.do")
public ModelAndView toUpload(MultipartFile photo, HttpSession session) throws IOException {
if(!photo.isEmpty()){
String path=session.getServletContext().getRealPath("\\img");
String filename=photo.getOriginalFilename();
if(filename.endsWith(".png")||filename.endsWith(".jpg")){
File file=new File(path,filename);
photo.transferTo(file);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("filename",filename);
modelAndView.setViewName("forward:/success.jsp");
return modelAndView;
}
}
return new ModelAndView("forward:/fail.jsp");
}
文件下载
@RequestMapping("/download.do")
public ResponseEntity<byte[]> filedownload(String filename,
HttpServletRequest request)throws IOException{
String path = request.getServletContext().getRealPath("\\img");
File file = new File(path,filename);
HttpHeaders header = new HttpHeaders();
header.setContentDispositionFormData("attachment",filename);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>
(FileUtils.readFileToByteArray(file),header,
HttpStatus.OK);
}