当前位置: 代码迷 >> JavaScript >> JSP中流形式上载文件
  详细解决方案

JSP中流形式上载文件

热度:136   发布时间:2012-09-04 14:19:30.0
JSP中流形式下载文件

<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=UTF-8" language="java"
	import="java.io.*,java.net.*,java.util.*;" errorPage=""%>
<%
	/**
	*  @author migle  2011-4-1
	*   流形式下载文件    downloadfile.jsp?fc=filecode   
	*
	*   在map中通过filecode查找具体文件路径
	***/
    String filecode = request.getParameter("fc") != null ? request
		    .getParameter("fc") : "";
	//可以扩展到从数据库或配置文件中读取
    Map<String, String> map = new HashMap<String, String>();
    map.put("999","d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_0.xls");
    map.put("70", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_70.xls");
    map.put("71", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_71.xls");
    map.put("72", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_72.xls");
    map.put("73", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_73.xls");
    map.put("74", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_74.xls");
    map.put("75", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_75.xls");
    map.put("76", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_76.xls");
    map.put("77", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_77.xls");
    map.put("79", "d:/qhBI/downloadFile/market_survey_data_report/market_survey_data_report_79.xls");

    if (map.containsKey(filecode)) {
		response.reset();
		File file = new File(map.get(filecode));
		//处理中文编码问题,IE9没有问题
		String fileName = URLEncoder.encode(file.getName(), "UTF-8");
		response.setContentType("application/octet-stream; charset=UTF-8");
		response.addHeader("Content-disposition"," attachment; filename=\"" + fileName + "\"");
		FileInputStream fis = null;
		OutputStream os = null;

		try {
		    //out.clear();
			//可以扩展到从FTP等网络中读取
		    os = response.getOutputStream();
		    fis = new FileInputStream(file);
		    byte[] b = new byte[1024];
		    int i = 0;
		    while ((i = fis.read(b)) > 0) {
			os.write(b, 0, i);
		    }
		    os.flush();
		} catch (Exception e) {
		    e.printStackTrace();
		} finally {
		    if (fis != null) {
			fis.close();
			fis = null;
		    }
		    if (os != null) {
			os.close();
			os = null;
		    }
		    if (out != null) {
			out.clear();
			out = pageContext.pushBody();
		    }
		}
    } else {
		response.setStatus(404);
		out.write("404 NOT FOUND! 你懂的");
    }
%>
?直接上代码了
  相关解决方案