package com.yanzuoguang.cloud.helper;

import com.yanzuoguang.util.helper.HttpHelper;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * HTTP文件
 * @author 颜佐光
 */
public class HttpFileHelper extends HttpHelper {
    
    /**
     * 下载文件
     *
     * @param serverFilePath 下载文件来源路径
     * @param saveFileName   文件保存名称
     * @param response       输出对象
     * @throws IOException 异常信息
     */
    public static void localToDown(String serverFilePath, String saveFileName, HttpServletResponse response) throws IOException {
        //获取文件的长度
        File file = new File(serverFilePath);
        //设置文件输出类型
        response.setContentType("application/octet-stream");
        // 设置下载的文件名
        response.setHeader("Content-disposition", "attachment; filename=" + new String(saveFileName.getBytes("utf-8"), "UTF-8"));
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(file.length()));
        ServletOutputStream bos = response.getOutputStream();
        // 获取输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(serverFilePath));
        try {
            //输出流
            byte[] buff = new byte[2048];
            int readSize = 1;
            while (readSize > 0) {
                readSize = bis.read(buff, 0, buff.length);
                if (readSize > 0) {
                    bos.write(buff, 0, readSize);
                }
            }
        } finally {
            bis.close();
        }
    }
}