outputInfo.java 2.8 KB
package com.servlet.bksh.DMC;

import java.io.FileInputStream;
import java.io.IOException;

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

public class outputInfo extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
//		String name = new String(request.getParameter("name").getBytes(
//				"ISO-8859-1"), "UTF-8");
		String name = request.getParameter("name");
		String pathtype = request.getParameter("type");

//		String dir = this.getServletContext().getRealPath("/");
		String dir =  "/usr/bk_cx/";
		//String dir =  "C://";
		String aFilePath = null; // 要下载的文件路径
		String aFileName = null; // 要下载的文件名
		FileInputStream in = null; // 输入流
		ServletOutputStream out = null; // 输出流
		String type = null;
		if (pathtype.equals("info"))
			aFilePath = dir + "bksh_info";
		else if (pathtype.equals("report"))
			aFilePath = dir + "bksh_report";
		else if (pathtype.equals("scheme"))
			aFilePath = dir + "bksh_scheme";
		try {
			aFileName = name;// 某个文件
			if (aFileName.endsWith(".xls") || aFileName.endsWith(".xlsx")) {
				type = "applicationnd.ms-excel";
			} else if (aFileName.indexOf(".pdf") > 0) {
				type = "applicationf";
			} else if ((aFileName.indexOf(".doc") > 0)
					|| (aFileName.indexOf(".docx") > 0)) {
				type = "application/msword";
			} else if (aFileName.indexOf(".txt") > 0) {
				type = "text/plain";
			} else if (aFileName.indexOf(".ppt") > 0) {
				type = "applicationt";
			} else if ((aFileName.indexOf(".jpg") > 0)
					|| (aFileName.indexOf(".jpeg") > 0)) {
				type = "image/jpeg";
			}
			response.setContentType(type + "charset=UTF-8");
			response.setHeader("Content-disposition", "attachment; filename="
					+java.net.URLEncoder.encode(aFileName, "UTF-8"));
			in = new FileInputStream(aFilePath +"/"+ name); // 读入文件
			out = response.getOutputStream();
			out.flush();
			int aRead = 0;
			while ((aRead = in.read()) != -1 & in != null) {
				out.write(aRead);
			}
			out.flush();
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}
}