public class FileLoad extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//1.获得下载对象的下载地址
String realPath = "E:\\JAVA\\JavaWeb\\MyServlet\\target\\MyServlet\\WEB-INF\\classes\\飞剑.png";
//2.获得下载对象的名称,非常精妙
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.想办法让浏览器支持我们能下载
resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
//4.获取下载文件的输入流
FileInputStream in= new FileInputStream(realPath);
//5.创建缓冲区buffer
int len =0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.写入到buffer,将缓冲区的数据输出到客户端
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
//8.关闭资源
in.close();
out.close();
}