import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class FileServlet extends HelloServlet {
/*由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取下载文件的路径
String realPath = "G:\\JavaWeb学习\\javaweb-servlet2\\servlet2.1\\target\\classes\\img\\照片.jpg";
//G:\JavaWeb学习\javaweb-servlet2\servlet2.1\target\classes\img\照片.jpg
System.out.println("下载文件的路径:"+realPath);
//2.下载文件名是啥?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.设置想办法让浏览器能够支持下载我们需要的东西
resp.setHeader("Content-Disposition","attachment;filename"+fileName);
//4.获取下载文件的输入流
FileInputStream inputStream = new FileInputStream(realPath);
//5创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileInputStream流写入到buffer缓冲区
while ((len=inputStream.read(buffer))>0){
out.write(buffer,0,len);
}
//8.使用OutputStream将缓冲区中的数据输出到客户端!
inputStream.close();
out.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}