文件的下载:
1). 步骤:
I. 设置 contentType 响应头: 设置响应的类型是什么 ? 通知浏览器是个下载的文件
response.setContentType("application/x-msdownload");
II. 设置 Content-Disposition 响应头: 通知浏览器不再有浏览器来自行处理(或打开)要下载的文件, 而由用户手工完成
response.setHeader("Content-Disposition", "attachment;filename=abc.txt");
III. 具体的文件: 可以调用 response.getOutputStream 的方式, 以 IO 流的方式发送给客户端.
OutputStream out = response.getOutputStream();
String pptFileName = "C:\\Users\\Think Pad\\Desktop\\__正在上课__\\11.尚硅谷_JavaWEB_监听器.pptx";
InputStream in = new FileInputStream(pptFileName);
byte [] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
in.close();
out不用关闭,是提供给用户的!
1 import java.io.FileInputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.OutputStream; 5 import java.net.URLEncoder; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 /** 13 * Servlet implementation class DownloadServlet 14 */ 15 public class DownloadServlet extends HttpServlet { 16 private static final long serialVersionUID = 1L; 17 18 /** 19 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 20 */ 21 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 22 response.setContentType("application/x-msdownload"); 23 24 String fileName = "文件下载.pptx"; 25 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 26 27 OutputStream out = response.getOutputStream(); 28 String pptFileName = "C:\\Users\\Think Pad\\Desktop\\__正在上课__\\JavaWEB_监听器.pptx"; 29 30 InputStream in = new FileInputStream(pptFileName); 31 32 byte [] buffer = new byte[1024]; 33 int len = 0; 34 35 while((len = in.read(buffer)) != -1){ 36 out.write(buffer, 0, len); 37 } 38 39 in.close(); 40 } 41 42 }
时间: 2024-11-02 23:36:30