<%@ page import="java.io.*;"%>
<%
try {
String url = "D:/websrc/aaa.doc";// 实际文件路径
String name = "默认中文文件名.doc";//显示给用户看的文件名,即ie弹出下载框中提示保存的文件名
//response.reset();
response.setContentType("bin");
response.setHeader("Content-Disposition", "attachment; filename="+name);//处理默认文件名的中文问题 ServletOutputStream os = response.getOutputStream();
FileInputStream in = new FileInputStream(url);
byte[] data = new byte[1024];
int temp = -1;
while((temp=in.read(data))!= -1){
os.write(data,0,temp);
os.flush();
}//while//
in.close();
os.close();
} catch(Exception e) {
out.print(e.toString());
}
%>
<%
try {
String url = "D:/websrc/aaa.doc";// 实际文件路径
String name = "默认中文文件名.doc";//显示给用户看的文件名,即ie弹出下载框中提示保存的文件名
//response.reset();
response.setContentType("bin");
response.setHeader("Content-Disposition", "attachment; filename="+name);//处理默认文件名的中文问题 ServletOutputStream os = response.getOutputStream();
FileInputStream in = new FileInputStream(url);
byte[] data = new byte[1024];
int temp = -1;
while((temp=in.read(data))!= -1){
os.write(data,0,temp);
os.flush();
}//while//
in.close();
os.close();
} catch(Exception e) {
out.print(e.toString());
}
%>
我的tomcat4.1.7如果在页面里加上<%@ page contentType="text/html;charset=gb2312"%>的话,汉字就会乱码。
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%
String filename = "";
if (request.getParameter("file") != null) {
filename = request.getParameter("file");
}
response.setContentType("application/msword");
response.setHeader("Content-disposition","attachment; filename="+filename);
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();
}
return;
%>这个方法,我试过,成功的
祝你好运!
<%
String filename = "t.doc";
// if (request.getParameter("file") != null) {
// filename = request.getParameter("file");
// }
response.reset();
response.setContentType("application/msword");
// response.setHeader("Content-disposition","attachment; filename="+filename);
response.addHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
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();
}
// return;
%>和你的有区别吗?