package cn.base.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

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

import cn.base.bean.BeanHelper;

@SuppressWarnings("serial")
public class DownloadServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fis = null;
		OutputStream toClient = null;
		try {
			String fullPath;
			String Path = request.getParameter("path");
			String downloadType = request.getParameter("privatePath");
			String localPath="";//对提取出来的文件名进行gbk编码
			if(Path.equals(new String(Path.getBytes("GB2312"), "GB2312"))){
				localPath = new String(Path.getBytes("GB2312"),"GBK"); 
	    	}else  if(Path.equals(new String(Path.getBytes("iso-8859-1"), "iso-8859-1"))){
	    		localPath = new String(Path.getBytes("iso-8859-1"),"GBK");;
	    	}else if(Path.equals(new String(Path.getBytes("UTF-8"), "UTF-8"))){
	    		localPath = new String(Path.getBytes("UTF-8"),"GBK");
	    	}else if(Path.equals(new String(Path.getBytes("GBK"), "GBK"))){
	    		localPath = new String(Path.getBytes("GBK"),"GBK");
	    	}
			String pacPath = "";
			if (downloadType.equals("versionPath")){
				pacPath = BeanHelper.getModuleConfFactory().getScatter().getVersionPath(); //private.xml中读取文件存放路径
			}else if(downloadType.equals("downPath")){
				pacPath = BeanHelper.getModuleConfFactory().getScatter().getDownPath(); //private.xml中读取文件存放路径
			} else if (downloadType.equals("serverPath")){
				pacPath = request.getSession().getServletContext().getRealPath("/"); //服务器路径
			}
			fullPath = pacPath + localPath; //文件的全路径
			System.out.println("*********************************fullPath===="+fullPath);
			String fileName = localPath.substring(localPath.lastIndexOf("/") + 1);
			fis = new FileInputStream(fullPath);
			int i = fis.available(); // 得到文件大小
			byte data[] = new byte[i];
			fis.read(data); // 读数据
			fis.close();
			String filenames = new String( fileName.getBytes("gbk"),"ISO8859-1");
			System.out.println("*********************************filenames===="+fullPath);
			response.setHeader("Content-Disposition", "attachment;fileName=" + filenames); // 设置文件头
			response.setContentLength(i);
			toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
			toClient.write(data); // 输出数据
			toClient.close();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			//try中途发生异常后关闭所有IO流
			closeAllIO(toClient, fis);
		}
	}
	
	//关闭所有IO流
	private void closeAllIO(OutputStream toClient,FileInputStream fis) {
		try {
			if(toClient != null)
				toClient.close();
			if(fis != null) 
				fis.close();
		}catch(IOException e) {
			//iLog.error("IO关闭失败："+e);
		}
	}
}
