package com.yeejoin.amos.boot.module.hygf.api.util;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class FileUtil {

	public static void downloadResource(String fileName, String resourceName, HttpServletResponse response) {
		DataInputStream in = null;
		OutputStream out = null;
		InputStream fileInputStream = null;
		try {
			response.reset();
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
			ClassPathResource classPathResource = new ClassPathResource(resourceName);
			fileInputStream = classPathResource.getInputStream();
			in = new DataInputStream(fileInputStream);
			out = response.getOutputStream();
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.reset();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
