1.文件的下载过程
1.获得文件的路径
2.下载文件名
3.设置让浏览器能支持我们需要的东西
4.获得下载文件的输入流
5.创建缓冲区
6.获得outputstream对象
7.将fileoutputstream流写入到buffer缓冲区
8.使用outputstream将缓冲区中的数据输出到客户端
缓冲区位于内存中,目的是将硬盘中内容调入缓冲区然后输出到客户端,这样能加快传输速度
2.文件的上传
1)过程
1.建立diskFileItemFactory对象,处理上传路径和大小限制
2.获得ServletFileupload
3.处理上传文件
2)注意
1.采用表单form提交
2.get请求有大小限制,post提交没有限制
3.form的添加属性:enctype=“multipart/form-data”
文件上传,这里以图片上传为例
@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);
}