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! 你懂的");
    }
%>
 直接上代码了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值