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. }  

 

转载于:https://www.cnblogs.com/qingfengmuyang/p/4025404.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值