servlet代码片段:
private
static
final
int
BUFSIZE =
4096
;
private
String filePath;
public
void
init() {
// the file data.xls is under web application folder
filePath = getServletContext().getRealPath(
""
) + File.separator +
"data.xls"
;
}
protected
void
doGet(HttpServletRequest request,
HttpServletResponse response)
throws
ServletException, IOException {
File file =
new
File(filePath);
int
length =
0
;
ServletOutputStream outStream = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(filePath);
// sets response content type
if
(mimetype ==
null
) {
mimetype =
"application/octet-stream"
;
}
response.setContentType(mimetype);
response.setContentLength((
int
)file.length());
String fileName = (
new
File(filePath)).getName();
// sets HTTP header
response.setHeader(
"Content-Disposition"
,
"attachment; filename=\""
+ fileName +
"\""
);
byte
[] byteBuffer =
new
byte
[BUFSIZE];
DataInputStream in =
new
DataInputStream(
new
FileInputStream(file));
// reads the file's bytes and writes them to the response stream
while
((in !=
null
) && ((length = in.read(byteBuffer)) != -
1
))
{
outStream.write(byteBuffer,
0
,length);
}
in.close();
outStream.close();
}
注:别直接在jsp页面实现文件下载,因为jsp仅只用来输入文字而已。
原文地址: http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html