package com.iformall.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author luozukai
 * 文件下载
 * @date 2019/2/13 15:32
 */
public class DownFileUtil {

    public static void downFile(String filePath,String exportFileName, HttpServletResponse response,
                         HttpServletRequest req) throws IOException {
        response.reset();
        response.setContentType("bin");
        String agent = req.getHeader("user-agent");
        if (agent.contains("Firefox")) {
            response.setHeader("Content-disposition",
                    "attachment; filename="
                            + new String(exportFileName.getBytes("GB2312"),
                            "ISO-8859-1"));
        } else {
            response.setHeader("Content-disposition",
                            "attachment; filename="
                                    + java.net.URLEncoder.encode(exportFileName,
                                    "UTF-8"));
        }
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len;
        InputStream inStream = new FileInputStream(filePath);
        while ((len = inStream.read(b)) > 0)
            response.getOutputStream().write(b, 0, len);
        inStream.close();
    }
}
