package com.sifang.modules.sys.util;

//import com.sf.file.alioss.AliyunOSSClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.ErrorListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.URL;
import java.net.URLEncoder;

public class CommonDownload {
    private static Logger logger = LoggerFactory.getLogger(CommonDownload.class);

    /**
     * 下载
     * @param request
     * @param response
     */
    public static void imgDownload(HttpServletRequest request, HttpServletResponse response){
        BufferedInputStream dis = null;
        BufferedOutputStream fos = null;
        String urlString = request.getParameter("path");
        String fileGS = request.getParameter("fileGS");
        String name = request.getParameter("name");
        String fileName = name+fileGS;// fileGS是文件格式如 .jpg, .xlxs, .jpg需要注意文件格式前有个.
        try {

            URL url = new URL(urlString);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));

            dis = new BufferedInputStream(url.openStream());
            fos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
                fos.write(buff, 0, bytesRead);
            }

        } catch (Exception e) {
            logger.error("downloadFile Exception {}",e);
            e.printStackTrace();
        } finally {
            if (dis != null)
                try{
                    dis.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            if (fos != null)
                try{
                    fos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

        }
    }

}
