- package com.itheima.servlet;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- //实现文件的下载
- public class ServletContextDemo6Servlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //得到输入流:路径该怎么获取
- String path = "/WEB-INF/2.jpg";// 斜线就代表当前应用
-
- //告知客户端以下载的方式打开
- //这个setHeader() 方法里面具体应该写什么
- response.setHeader("Content-Disposition", "attachment;filename=2.jpg");
- response.setHeader("Content-Type", "application/octet-stream");
-
- String realPath = getServletContext().getRealPath(path);//根据相对于当前应用的路径,得到绝对路径
- System.out.println(realPath);
- InputStream in = new FileInputStream(realPath);
- OutputStream out = response.getOutputStream();
-
- int len = -1;
- byte b[] = new byte[1024];
- while((len=in.read(b))!=-1){
- out.write(b, 0, len);
- }
- in.close();
- out.close();
-
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
复制代码
//这个setHeader() 方法里面具体应该写什么
response.setHeader("Content-Disposition", "attachment;filename=2.jpg");
response.setHeader("Content-Type", "application/octet-stream");
|