package com.mahe666.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;

public class FileDownload extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载文件的路径
            // getRealPath 代表的是绝对路径，target里面的项目路径，/ 代表项目路径下
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/picture.png");
        System.out.println("下载文件的路径："+realPath);
        //下载的文件名是什么
        String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
        //设置 想办法让浏览器能够支持我们需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
            //中文文件名 URLEncoder.encode 编码，否则有可能乱码
            //resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
        //获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //将FileOutputStream流写到buffer缓冲区
        while ((len=in.read(buffer))>0){
            //使用OutputStream将缓冲区的数据输出到客户端
            out.write(buffer,0,len);
        }
        //关闭流
        in.close();
        out.close();
    }

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