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 DownloadFileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.下载路径
String filePath = "D:\\Desktop\\工具箱\\图片素材\\imm.png";
System.out.println("下载路径 = " + filePath);
//获取文件名
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
resp.setHeader("Content-Disposition","attachment;filename="+fileName);
//获取下载文件的输入流
FileInputStream in = new FileInputStream(filePath);
//创建缓冲区域
int len = 0;
byte[] buffer = new byte[1024];
//获取输出流
ServletOutputStream out = resp.getOutputStream();
while ((len=in.read(buffer)) > 0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
}