package com.tuoheng.admin.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Slf4j
public final class DownloadUtil {

    /**
     *
     * 下载
     *
     * @param response
     * @param filePath
     * @param fileName
     */
    public static void download(HttpServletResponse response, String filePath, String fileName) {
        //清空缓存
        response.reset();
        // 定义浏览器响应表头，并定义下载名

        try {
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setCharacterEncoding("utf-8");
        //定义下载的类型
        response.setContentType("application/msword;charset=UTF-8");

        File files = new File(filePath);
        OutputStream out = null;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(files);
            //3.通过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = inputStream.read(buffer);
                //4.写到输出流(out)中
                out.write(buffer, 0, b);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                inputStream.close();
                out.close();
                out.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        log.info("下载结束......");
    }

}
