MENU

RestFul文件上传与下载(待)

April 1, 2022 • 默认分类

上传
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value="img")MultipartFile img, HttpServletRequest request)

       throws Exception {
   //getSize()方法获取文件的大小来判断是否有上传文件
   if (img.getSize() > 0) {
      //获取保存上传文件的file文件夹绝对路径
      String path = request.getSession().getServletContext().getRealPath("file");
      //获取上传文件名
      String fileName = img.getOriginalFilename();
      File file = new File(path, fileName);
      img.transferTo(file);
      //保存上传之后的文件路径
      request.setAttribute("filePath", "file/"+fileName);
      return "upload";
    }
  return "error";

}
// 多文件上传
//和单文件上传类似,input的name属性要一致,接收的参数需要是数组类型
@RequestMapping(value="/uploads", method = RequestMethod.POST)
public String uploads(@RequestParam MultipartFile[] imgs, HttpServletRequest request)

       throws Exception {
   //创建集合,保存上传后的文件路径
   List<String> filePaths = new ArrayList<String>();
   for (MultipartFile img : imgs) {
       if (img.getSize() > 0) {
          String path = request.getSession().getServletContext().getRealPath("file");
          String fileName = img.getOriginalFilename();
          File file = new File(path, fileName);
          filePaths.add("file/"+fileName);
          img.transferTo(file);
        }
   }
   request.setAttribute("filePaths", filePaths);
   return "uploads";

}
下载
中文文件名乱码,对应的文件名 encode一次以及header中设置时多一个参数filename*=指定编码格式
@RequestMapping("/download")
public void downloadFile(String fileName,HttpServletRequest request,

   HttpServletResponse response){
 if(fileName!=null){
   //获取file绝对路径
   String realPath = request.getServletContext().getRealPath("file/");
   File file = new File(realPath,fileName);
   OutputStream out = null;
   if(file.exists()){
      //设置下载类型,具体百度
      response.setContentType("application/force-download");
      //设置文件名 
      response.setHeader("Content-Disposition", "attachment;filename="+fileName);
      try {
         out = response.getOutputStream();
           //写入前台页面
         out.write(FileUtils.readFileToByteArray(file));
         out.flush();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }finally{
          if(out != null){
              try {
                 out.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
      }                    
   }           
}           

}