servlet实现文件下载

 
  
ServletContext sct = this.getServletContext();
//设置响应头,控制浏览器下载
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("111.txt", "UTF-8"));
//也可以使用response.setContentType(MIME)来设置MIME,MIME常使用类型:
// text/html:告诉浏览器已html形式显示response响应对象中的内容
// applaction/jar:告诉浏览器下载内容
// ...
//response.setContentType("applaction/jar");
//获取输入流,/代表项目根路径
InputStream in = sct.getResourceAsStream("/111.txt");
//获取响应输出流,将文件以二进制形式写到响应对象中,即response
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while((read = in.read(buffer)) != -1) {
	out.write(buffer, 0, read);
}
out.flush();
out.close();

response提供了两种输出流,response.getOutputStream()获取二进制输出流,response.getWriter()获取字符输出流

你可能感兴趣的:(servlet实现文件下载)