使用servlet的方式下载:
简单的将部分核心代码摘录下来,如下
简单的将部分核心代码摘录下来,如下
/**
* 下载文档
* @author 张国明 guomingzhang2008@gmail.com
* @version 2012-11-26 上午10:13
*/
public void download() {
OutputStream os = null;
InputStream is = null;
try {
os = response.getOutputStream();
is = new FileInputStream("d:/zhangm.txt");
// 可以下载任意类型的文件
response.setContentType("application/octet-stream");
// 设置文件编码
response.setCharacterEncoding("UTF-8");
// 解决中文文件名乱码的问题
String fileName = new String("张国明.txt".getBytes(), "iso8859-1");
// 设置文件以附件的方式进行下载
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
// 以字节的方式读入源文件,并将读入的字节输出到目标文件中
byte[] tempByte = new byte[1024];
int length = 0;
while ((length = is.read(tempByte)) != -1) {
os.write(tempByte, 0, length);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.getMessage();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.getMessage();
}
}
}
}
本文介绍了一种使用Servlet实现文件下载的方法。通过设置HTTP响应头,指定文件类型为二进制流,解决文件名中文乱码问题,并实现了文件的逐块读取及输出。

被折叠的 条评论
为什么被折叠?



