package com.jeeplus.pubmodules.oss.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author: 徐滕
 * @version: 2023-10-30 10:43
 */
public class FileUtil {

    /**
     * MultipartFile转File
     * @param file
     * @return
     * @throws IOException
     */
    public static File transformMultipartFile(MultipartFile file) throws IOException {
        File srcFile = null;
        //MultipartFile转File
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            srcFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, srcFile);
            ins.close();
        }
        return srcFile;
    }

    /**
     * 获取流文件
     * @param ins
     * @param file
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
