package com.younike.store.config;
import org.springframework.core.io.ByteArrayResource;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author: zulu.chen
 * @date: 2021/10/28/11:35
 * @description:
 */


public class FileResource extends ByteArrayResource {

    private String filename;

    public FileResource(File file) throws IOException {
        super(getBytesByFile(file));
        this.filename = file.getName();
    }

    @Override
    public String getFilename() {
        return this.filename;
    }

    public static byte[] getBytesByFile(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
