1.首先在maven项目下创建java class 类 ,然后继承HttpServlet接口。 重写doGet方法。
2.代码如下
点击查看代码
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;
public class response extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取文件下载路径
// String realPath = this.getServletContext().getRealPath("/1.png");
String realPath="F:\\demo\\maven01\\response01\\target\\classes\\1.png";
//2.下载文件命是啥
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.设置想办法让浏览器能够(Content-Disposition)支持下载我们需要的东西
resp.setHeader("Content-Disposition","attachment;filename="+filename);
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len=0;
byte[] buffer = new byte[1024];
//6.获取OutputStream 对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileOutputStream 流写入buffer缓冲区
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
}