DownloadServlet
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String realPath = this.getServletContext().getRealPath("");获取本地文件路径,前提在此目录下确实存在这个文件
String realPath = this.getServletContext().getRealPath("\images\img01.jpg");
// 获取下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
System.out.println(fileName);
// 让浏览器能支持我们下载我们需要的东西
// resp.setHeader("Content-Disposition", "attchment;filename=" + fileName);
// 当文件名为中文时, 会输出不成功, 将使用以下方法解决
resp.setHeader("Content-Disposition", "attchment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 获取outputStream对象
ServletOutputStream servletOutputStream = resp.getOutputStream();
while((len = fileInputStream.read(buffer)) > 0){
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.close();
fileInputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}