文件下载
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取文件路径
String realPath = "D:\\javaweb-02-maven\\servlet-01\\src\\main\\resource\\img.png";
//D:\javaweb-02-maven\servlet-01\src\main\resource\img.png
System.out.println("下载路径"+realPath);
//下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//让浏览器能支持所下载的的东西
resp.setHeader("Content-disposition","attachment;filename"+filename);
//获得下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//创建缓冲区
int len=0;
byte[] buffer=new byte[1024];
//获得OutputStream流
ServletOutputStream outputStream = resp.getOutputStream();
//将FileInputStream写到缓冲区
while((len=fileInputStream.read(buffer))>0){
outputStream.write(buffer,0,len);
}
//关闭流保证安全
fileInputStream.close();;
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
```
`