JSP学习笔记(四十七):以文件流方式读取文件,并且强制下载

本文代码以servlet方式实现,其他方式可以做适当调整:

public class MyClass extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 输入流 FileInputStream
FileInputStream inputStream = new FileInputStream("c:/myapp.rar");

// 输出流 ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

// 下面5行代码实现从输入流 FileInputStream 到 输出流 ByteArrayOutputStream 写入的过程
byte[] buffer = new byte[1024];
int iLength = 0;
while ((iLength = inputStream.read(buffer)) != -1) {
outputStream.write(buffer,
0, iLength);
}

// 通知response的输出类型,输出方式及输出内容
resp.addHeader("Content-Disposition", "attachment; filename=myapp.rar");
resp.setContentType(
"application/octet-stream");
resp.setContentLength(outputStream.size());

ServletOutputStream out
= resp.getOutputStream();
outputStream.writeTo(out);
out.flush();

inputStream.close();
outputStream.close();
}
}

 

posted @ 2008-09-15 01:24  魔豆  阅读(1956)  评论(0编辑  收藏  举报