outputInfo_yld.java 2.7 KB
package com.servlet.bkyld;

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_yld extends HttpServlet {

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

	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 =request.getParameter("name");
		String pathtype = request.getParameter("type");

//		String dir = this.getServletContext().getRealPath("/");
		String dir =  "/usr/bk_cx/";
		String aFilePath = null; // 要下载的文件路径
		String aFileName = null; // 要下载的文件名
		FileInputStream in = null; // 输入流
		ServletOutputStream out = null; // 输出流
		String type = null;
		if (pathtype.equals("info"))
			aFilePath = dir + "bkyld_info";
		else if (pathtype.equals("report"))
			aFilePath = dir + "bkyld_report";
		else if (pathtype.equals("scheme"))
			aFilePath = dir + "bkyld_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 + "/" + aFileName); // 读入文件
			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();
			}
		}
	}

}