在用JSP下载某些文件时,可能会碰到文件直接用IE打开了的情况。下面的方法可以解决这问题:
downloadTest.jsp:
<%@page contentType="text/html; charset=EUC-JP" language="java" %>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "
http://www.w3.org/TR/html4/strict.dtd";>
<% String fileName="";
if (request.getParameter("file") != null) {
fileName = request.getParameter("file");
}
if("1".equals(request.getParameter("downloadFlag"))){//downloadFlag为1时为下载文件
response.setHeader("Content-disposition","attachment; filename="+fileName);
}else if("0".equals(request.getParameter("downloadFlag"))){//downloadFlag为0时为用指定的程序打开文件
response.setContentType("application/ms-word");
}//downloadFlag为其他值时用IE默认的方式打开文件
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + fileName)));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
%>
这里,我是用test.doc(与downloadTest.jsp处于同一目录)来做下载文件的,请求时的url为:
http://127.0.0.1:8080/downloadTest.jsp?file=test.doc&downloadFlag=x
x=0时代表你用指定的程序打开文件
x=1时代表你要下载文件
x=其他值时代表你按IE的默认方式处理