开发中文件上传做得多了,文件下载都是第一次遇到;原理就是往后台的输出流写入文件的内容,现总结如下:
public void downLoad(String filePath, String contentType) throws Exception {
// System.out.println(filePath);
File f = new File(filePath);
if (!f.exists()) {
res.sendError(404, "对不起,下载文件没有找到,无法下载!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
//res为请求对应的HttpServletResponse对象
res.reset(); // 非常重要
res.setContentType(contentType + ";charset=utf-8");
res.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
OutputStream out = res.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.flush();
out.close();
}
至于 res.setContentType(contentType + ";charset=utf-8"); 中setContentType的值根据不同的文件类型不同有相应不同的写法 对应关系大体如下:
(注:如果文件后缀名为avi则写 res.setContentType("video/avi") )
avi-----video/avi
bmp-----application/x-bmp
doc-----application/msword
gif-----image/gif
htm或者html-----text/html
jpg或者jpeg-----image/jpeg
mht或者mhtml-----message/rfc822
mp3-----audio/mp3
ppt-----application/vnd.ms-powerpoint
pptx-----application/vnd.openxmlformats-officedocument.presentationml.presentation
rm-----application/vnd.rn-realmedia
rmvb-----application/vnd.rn-realmedia-vbr
xls-----application/x-xls
xml-----text/xml
rar-----application/octet-stream
zip-----application/x-zip-compressed
swf-----application/x-shockwave-flash
wav-----audio/wav
txt-----text/plain
excel/zip:data/Application