package cn.reghao.oss.console.util;

import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2021-06-04 10:18:11
 */
@Service
public class UploadDownload {
    public void download(File file, HttpServletResponse response) throws IOException {
        String filename = file.getName();
        prepareResponse(filename, response);

        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = response.getOutputStream();
        download(bis, os);
    }

    public void download(String filename, InputStream in, HttpServletResponse response) throws IOException {
        prepareResponse(filename, response);
        download(in, response.getOutputStream());
    }

    private void prepareResponse(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()));
    }

    private void download(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int i = in.read(buffer);
        while (i != -1) {
            out.write(buffer, 0, i);
            i = in.read(buffer);
        }
        in.close();
        out.close();
    }
}
