package com.hz.his.util;

import feign.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件处理器
 */
public class FileDownUtil {

    /**
     * 获取文件转化工具
     * @param response 微服务返回
     * @param fileUrl 文件路径
     * @return
     */
    public static File downToFile(Response response,String fileUrl){
        Response.Body body = response.body();

        InputStream inputStream = null;
        String filePath ="";
        FileOutputStream fos = null;
        File downloadFile = null;

        try {
            //获取response中的文件流
            inputStream = body.asInputStream();

            //临时文件
            String suffix = fileUrl.substring(fileUrl.lastIndexOf("."));
            downloadFile = File.createTempFile("temp/", suffix);
            //写入文件
            fos= new FileOutputStream(downloadFile);
            byte[] c = new byte[1024];
            int length;
            while((length= inputStream.read(c))>0){
                fos.write(c,0,length);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(downloadFile != null){
                downloadFile.deleteOnExit();
            }
        }
        return downloadFile;
    }

}