使用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();
}
}
}
}