首页 > 代码库 > Springmvc文件上传与下载

Springmvc文件上传与下载

(上传)

1.jar包与springmvc.xml

 

将request包装成MultipartHttpServletRequest.

 

2.页面

注意method为post

3.action

  方法一解析(request)

方法二(参数)

 

(下载)

  1. @RequestMapping("/download/{fileName}")  
  2.     public ModelAndView download(@PathVariable("fileName")  
  3.     String fileName, HttpServletRequest request, HttpServletResponse response)  
  4.             throws Exception {  
  5.   
  6.         response.setContentType("text/html;charset=utf-8");  
  7.         request.setCharacterEncoding("UTF-8");  
  8.         java.io.BufferedInputStream bis = null;  
  9.         java.io.BufferedOutputStream bos = null;  
  10.   
  11.         String ctxPath = request.getSession().getServletContext().getRealPath(  
  12.                 "/")  
  13.                 + "\\" + "images\\";  
  14.         String downLoadPath = ctxPath + fileName;  
  15.         System.out.println(downLoadPath);  
  16.         try {  
  17.             long fileLength = new File(downLoadPath).length();  
  18.             response.setContentType("application/x-msdownload;");  
  19.             response.setHeader("Content-disposition", "attachment; filename="  
  20.                     + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
  21.             response.setHeader("Content-Length", String.valueOf(fileLength));  
  22.             bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
  23.             bos = new BufferedOutputStream(response.getOutputStream());  
  24.             byte[] buff = new byte[2048];  
  25.             int bytesRead;  
  26.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  27.                 bos.write(buff, 0, bytesRead);  
  28.             }  
  29.         } catch (Exception e) {  
  30.             e.printStackTrace();  
  31.         } finally {  
  32.             if (bis != null)  
  33.                 bis.close();  
  34.             if (bos != null)  
  35.                 bos.close();  
  36.         }  
  37.         return null;  
  38.     }  
  39. }  

 

Springmvc文件上传与下载