JavaWeb之getServletContext对象和文件下载

package study.web.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Base64;


@WebServlet("/response/demo3")
public class Demo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * ServletContext对象获取
         * 两种方式:
         *      通过request对象获取:
         *          ServletContext contentxt1 = req.getServletContext();
         *
         *      通过HttpServlet获取:
         *          ServletContext contentxt2 = this.getServletContext();
         *
         */

        /**
         * 获取文件的mime类型
         *  String file1 = "1.jpg";
         *  String mi = this.getServletContext().getMimeType(file1);
         *  System.out.println(mi);
         */


        //下载文件

        //文件名称
        String f1 = "052700005E68762CADA7B24DE20D3169.jfif";
        String f2 = "mda-ijpq9sxmv0ucizic.mp4";
        String f3= "绣春刀.mp4";

        try {
            download(req,resp,f3);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 下载文件
     * @param req 请求对象
     * @param resp 响应对象
     * @param file 下载文件名称
     * @throws Exception
     */
    public void download(HttpServletRequest req, HttpServletResponse resp,String file) throws Exception {

        //1、使用字节输入流加载文件进内存
        //找到文件
        ServletContext context = this.getServletContext();
//        String realPath = context.getRealPath("C:\\Users\\admin\\Pictures\\" + file);

        File realPath = new File("C:\\Users\\admin\\Pictures\\" + file);
        System.out.println("C:\\Users\\admin\\Pictures\\" + file);


        //读取文件流
        FileInputStream fis = new FileInputStream(realPath);



        //设置响应header 的mime #响应的文件类型通过 getServletContext 获取
        resp.setContentType(context.getMimeType(file));

        //解决中文文件名称乱码的问题
        String agent = req.getHeader("user-agent");
        String filename = getFileName(agent, file);
        //设置响应保持的文件名称
        resp.setHeader("content-disposition","sttachment;filename="+filename);

        //将文件流写入到输出流中
        ServletOutputStream sos = resp.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while ((len = fis.read(buff)) != -1){
            sos.write(buff,0,len);
        }


    }

    /**
     * 解决文件名称中文乱码的问题
     * @param agent
     * @param filename
     * @return
     * @throws Exception
     */
    public static String getFileName(String agent, String filename) throws Exception {
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            Base64.Encoder encoder = Base64.getEncoder();
            filename = "=?utf-8?B?" + encoder.encodeToString(filename.getBytes("utf-8")) + "?=";
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}

Java文件下载.png

NOTE:

  1. 获取文件的mime类型
  2. 文件流读取和输出
  3. 文件下载和中文名称乱码

仅有一条评论

添加新评论