package cn.quantgroup.customer.rest;

import cn.quantgroup.customer.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * 文件下载
 *
 * @author tao
 * @version 2020-09-30 17:12
 */
@Controller
@RequestMapping("/download")
public class FileRest {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IFileService fileService;


    // 文件下载相关代码
    @RequestMapping("/settle_prove/{loanId}")
    public String downloadFile(HttpServletResponse response, @PathVariable Long loanId) throws Exception {

        BufferedInputStream bis = fileService.getBufferedInputStream(loanId);
        if (bis != null) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            //response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            //response.setContentType("multipart/form-data;charset=UTF-8");也可以明确的设置一下UTF-8，测试中不设置也可以。
            response.setHeader("Content-Disposition", "attachment;fileName="+ new String(("结清证明_"+loanId).getBytes("GB2312"),"ISO-8859-1"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            try {
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("下载成功");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


        return null;
    }

}
