package com.dubh.common.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 作者姓名: dubaohui
 * @version 创建时间：2015-8-12 下午7:17:21
 * 类说明
 */
public class Downfile {
	
	 public static void DownloadFile(HttpServletRequest request,HttpServletResponse response,String filename){
	        //获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		     String path = request.getSession().getServletContext().getRealPath("attached")+File.separator+filename;
		     File file = null;
			    try {
					file = new File(path);
				} catch (Exception e) {
					e.printStackTrace();
				}
			   
				if(null!=file){	
					if(file.exists()){
						try {
							//弹出下载对话框
							response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "utf-8"));
							OutputStream os = os=response.getOutputStream();
							InputStream is= is=new FileInputStream(file);
							BufferedInputStream bis=new BufferedInputStream(is);
							BufferedOutputStream bos= new BufferedOutputStream(os);
							//用输入流进行先读，然后用输出流去写
							int bytesRead = 0;
							byte[] buffer = new byte[8192];
							while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
							bos.write(buffer, 0, bytesRead);
							}
						   bos.flush();
						   bos.close();
						   bis.close();
						   os.flush();
						   os.close();
						   is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
	    } 
}
