web 服务器接收到客户端的 http 请求
针对这个请求,分别创建一个代表请求的 HttpServletRequest 对象,代表响应的 HttpServletResponse 对象
获取客户端请求过来的参数:HttpServletRequest
给客户端响应一些信息:HttpServletResponse
下载文件:
1.获取下载文件的路径
2.下载的文件名
3.让浏览器支持下载
4.获取下载文件的输入流
5.创建缓冲区
6.获取 OutputStream 对象
7.将 FileOutputStream 流写入到 buffer 缓冲区
8.使用 OutputStream 将缓冲区中的数据输出到客户端
pom.xml 导入 jar 包
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version><scope>provided</scope></dependency>
getRealPath 绝对路径,resources 放入需要下载的文件
substring 截取字符串
setHeader 文件头信息
resp.setHeader("Content-disposition","attachment;filename"+fileName);
new FileInputStream 输入流
new byte[1024]
getOutputStream 输出流
读数据、写数据
关闭流
web.xml 注册和映射:
<servlet><servlet-name>down</servlet-name><servlet-class>com.demo.response.FileDown</servlet-class></servlet><servlet-mapping><servlet-name>down</servlet-name><url-pattern>/down</url-pattern></servlet-mapping>
(如果重新创建了 Module,Smart Tomcat 也要添加一个自己创建的路径)
代码如下:
package com.demo.response;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;public class FileDown extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.获取下载文件的路径//getRealPath 绝对路径String realPath = this.getServletContext().getRealPath("/1.png");//String realPath = "D:\\IntelliJProject\\javaweb\\response\\target\\classes\\com\\1.png";//2.下载的文件名//substring 截取字符串 /需要转义,用\\,+1获取下一个String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//3.让浏览器支持下载//setHeader 文件头信息,固定写法resp.setHeader("Content-disposition","attachment;filename"+fileName);//URLEncoder.encode编码支持中文//resp.setHeader("Content-disposition","attachment;filename"+ URLEncoder.encode(fileName,"UTF-8"));//4.获取下载文件的输入流FileInputStream fileInputStream = new FileInputStream(realPath);//5.创建缓冲区int len = 0;byte[] buffer = new byte[1024];//6.获取 OutputStream 对象,输出流ServletOutputStream outputStream = resp.getOutputStream();//7.将 FileOutputStream 流写入到 buffer 缓冲区//8.使用 OutputStream 将缓冲区中的数据输出到客户端while ((len = fileInputStream.read(buffer))!=-1){ //>0也行outputStream.write(buffer,1,len); //从1到len长度}//IO流后开先关outputStream.close();fileInputStream.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}