将文件放置到resources目录下
![](https://i-blog.csdnimg.cn/blog_migrate/f6345b527c66130842c48821270ffc44.png)
编写自己的HttpServlet类
package org.example;
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.InputStream;
import java.net.URLEncoder;
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取要下载的文件的绝对路径
//在resources目录放入search.jpg,注意项目导出后resources中的文件被打包到/WEB-INF/classes下
String path = request.getServletContext().getRealPath("/WEB-INF/classes/search.jpg");
//或者直接写绝对路径
// String path = "E:\Language\JavaWeb\Learn\Learn1\target\classes\search.jpg";
//2.获取要下载的文件名
String fileName = path.substring(path.lastIndexOf("\\")+1);
//3.设置content-disposition响应头控制浏览器以下载的形式打开文件
//为避免乱码filename为utf-8编码
response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
//4.获取要下载的文件输入流
InputStream in=new FileInputStream(path);
int len=0;
//5.创建数据缓冲区
byte[] buffer = new byte[1024];
//6.通过response对象获取OutputStream流
ServletOutputStream out = response.getOutputStream();
//7.将FileInputStream流写入到buffer缓冲区
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
配置web.xml
<servlet>
<servlet-name>downloadServlet</servlet-name>
<servlet-class>org.example.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>