JSP下载文档

1、设置doc格式的文件弹出对话框:

 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<mime-mapping>
		<extension>doc</extension>
		<mime-type>application/vnd.ms-word</mime-type>
	</mime-mapping>

	<welcome-file-list>
		<welcome-file>DownloadFile.jsp</welcome-file>
	</welcome-file-list>
</web-app>
 

2、注意要主动释放out对象,否则会抛出错误:

<%@page language="java" contentType="application/x-msdownload"
	import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
	response.reset();//可以加也可以不加
	//设置为下载application/x-download
	response.setContentType("application/x-download");
	// /../../退WEB-INF/classes两级到应用的根目录下去,
	//注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
	System.out.println(this.getClass().getClassLoader()
			.getResource("/").getPath());
	String filenamedownload = this.getClass().getClassLoader()
			.getResource("/").getPath()
			+ "/../../系统解决方案.doc";
	String filenamedisplay = "系统解决方案.doc";//系统解决方案.txt
	filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
	response.addHeader("Content-Disposition", "attachment;filename="
			+ filenamedisplay);

	OutputStream output = null;
	FileInputStream fis = null;
	try {
		output = response.getOutputStream();
		fis = new FileInputStream(filenamedownload);

		byte[] b = new byte[1024];
		int i = 0;

		while ((i = fis.read(b)) > 0) {
			output.write(b, 0, i);
		}
		output.flush();
	} catch (Exception e) {
		System.out.println("Error!");
		e.printStackTrace();
	} finally {
		if (fis != null) {
			fis.close();
			fis = null;
		}
		if (output != null) {
			output.close();
			output = null;
		}
		//主动释放在jsp中使用的对象
		out.clear();
		out = pageContext.pushBody();
	}
%>

 运行结果:

/D:/tomcat6_Green/webapps/DownloadFile/WEB-INF/classes/
/D:/tomcat6_Green/webapps/DownloadFile/WEB-INF/classes/

 

参考:

1、tomcat5下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

2、JSP文件下载及getOutputStream () has  already  been 的解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值