CommonUtils.java 2.22 KB
Newer Older
1
package web.multitask.trismegistoservices.utils;
2

3 4 5 6 7 8
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
9

10 11 12
import java.io.File;
import java.io.IOException;
import java.util.Base64;
13

14 15
@Service
public class CommonUtils {
16

17
    private final String FILE_FOLDER = System.getProperty("java.io.tmpdir");
18

19 20 21 22
    public String multipartFileToBase64(MultipartFile file) throws IOException {
        byte[] byteArray = file.getBytes();
        return Base64.getEncoder().encodeToString(byteArray);
    }
23

24 25 26 27 28 29 30 31 32 33 34 35
    public File base64ToFile(String base64, String name) {
        try {
            byte[] byteArray = Base64.getDecoder().decode(base64);
            String folder = FILE_FOLDER + "/" + name;
            File outputFile = new File(folder);
            FileUtils.writeByteArrayToFile(outputFile, byteArray);
            return outputFile;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    public String fileToBase64(File file) {
        try {
            byte[] byteArray = FileUtils.readFileToByteArray(file);
            return Base64.getEncoder().encodeToString(byteArray);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public String byteToBase64(byte[] byteArray) {
        return Base64.getEncoder().encodeToString(byteArray);
    }

    public Resource byteToResource(byte[] byteArray, String name) {
        return new ByteArrayResource(byteArray) {
            @Override
            public String getFilename() {
                return name;
            }
        };
    }

    public Resource fileToResource(File file) {
        return new FileSystemResource(file);
    }

    public Resource base64ToResource(String base64, String name) {
        byte[] byteArray = Base64.getDecoder().decode(base64);
        return new ByteArrayResource(byteArray) {
            @Override
            public String getFilename() {
                return name;
            }
        };
    }
}