package com.template.common.utils;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;

public class MultipartFileUtils {

    public static MultipartFile base64ToMultipartFile (String s) {
        MultipartFile image = null;
        StringBuilder base64 = new StringBuilder("");
        if (s != null && !"".equals(s)) {
            base64.append(s);
            String[] baseStrs = base64.toString().split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(baseStrs[1]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int j = 0; j < b.length; ++j) {
                if (b[j] < 0) {
                    b[j] += 256;
                }
            }
            image = new  BASE64DecodedMultipartFile(b, baseStrs[0]);
        }
        return image;
    }
}
