package com.feijian.servlet;
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;
import java.io.InputStream;
import java.net.URLEncoder;
public class Response extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取下载文件的路径
String realPath = "E:\\JAVA\\JW\\javaweb\\Demo02\\src\\main\\resources\\飞剑.png";
System.out.println("下载文件路径:"+realPath);
//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、创建缓冲区
int len =0;
byte[] buffer = new byte[1024];
//6、获取outputStream对象
ServletOutputStream out = resp.getOutputStream();
//7、写入缓冲区
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
//8、缓冲区内容输出到客户端
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}