package com.ekexiu.portal.util;

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 javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownload extends HttpServlet {
	private String accessoryFolder;

	public String getAccessoryFolder() {
		return accessoryFolder;
	}

	public void setAccessoryFolder(String accessoryFolder) {
		this.accessoryFolder = accessoryFolder;
	}

	private static final long serialVersionUID = 1190786634322390349L;

	/**
	 * 文件下载
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取前台传回要下载的文件名
		String fileName = request.getParameter("fileName");
		// 获取下载文件的绝对路径path
		String path = this.accessoryFolder + "/" + fileName;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			// String ext = filename.substring(filename.lastIndexOf(".") +1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("GB2312"),"iso8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			// response.setContentType("application/octet-stream");
			// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	@Override
	public void init() throws ServletException {
		this.accessoryFolder = "D:/application/Workspaces/ekexiu.com.portal/src/main/webapp/accessory";
		super.init();
	}

}
