码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载

时间:2015-11-01 16:24:46      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

  //文件下载 主要方法
	  public static void download(HttpServletRequest request,HttpServletResponse response, String storeName, String contentType) throws Exception {  
	    request.setCharacterEncoding("UTF-8");  
	    BufferedInputStream bis = null;  
	    BufferedOutputStream bos = null;  
	
	    //获取项目根目录
	    String ctxPath = request.getSession().getServletContext().getRealPath("/resource/img/"); 
	    
	    //获取下载文件路径
	    String downLoadPath = ctxPath+"/"+storeName;  
	  
	    //获取文件的长度
	    long fileLength = new File(downLoadPath).length();  

	    //设置文件输出类型
	    response.setContentType("application/octet-stream");  
	    response.setHeader("Content-disposition", "attachment; filename="+ new String(storeName.getBytes("utf-8"), "ISO8859-1")); 
	    //设置输出长度
	    response.setHeader("Content-Length", String.valueOf(fileLength));  
	    //获取输入流
	    bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
	    //输出流
	    bos = new BufferedOutputStream(response.getOutputStream());  
byte[] buff = new byte[2048];
int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } //关闭流 bis.close(); bos.close(); }

  

 

//重定向下载文件
	@RequestMapping("admin/dowm")
	public ModelAndView download(HttpServletRequest request,HttpServletResponse response) throws Exception {
	    String storeName=request.getParameter("filename");
	    String contentType = "application/octet-stream";  
	     download(request, response, storeName, contentType);  
	    return null;  
	  }  

  

文件下载

标签:

原文地址:http://www.cnblogs.com/yabushan/p/4927858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!