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异常的原因和解决方法