base64图片文件上传OSS,下载OSS图片转换为InputStream,文件转base64,base64转文件工具类

发布时间 2023-08-18 23:49:45作者: oktokeep

base64图片文件上传OSS,下载OSS图片转换为InputStream,文件转base64,base64转文件工具类

OSSUtils.java

public class OSSUtils {
    private static Logger logger = LoggerFactory.getLogger(OSSUtils.class);

    private static final String ACCESS_ID = "阿里云oss参数accessId";
    private static final String ACCESS_KEY = "阿里云oss参数accessKey";

    public static final String OSS_END_POINT = "http://oss-cn-hangzhou.aliyuncs.com";

    //OSS cilent
    private static final OSSClient client = new OSSClient(OSS_END_POINT, ACCESS_ID, ACCESS_KEY);
    
    //base64图片文件上传OSS
    public boolean uploadAuthBase64FromPreUpdatePic(String key, String base64,String bucket) throws Exception {
        boolean errorCode = false;
        InputStream input = null;
        ObjectMetadata objectMeta = new ObjectMetadata();
        // 在metadata中标记文件类型
        objectMeta.setContentType("image/*");
        try {
            byte[] bytes = Base64Encoder.decode(base64.getBytes());
            objectMeta.setContentLength(bytes.length);
            input = new ByteArrayInputStream(bytes);

            PutObjectResult res = client.putObject(bucket, key, input, objectMeta);
            logger.info("PutObjectResult res=" + GsonUtils.toJson(res));
            // 校验文件MD5值
            errorCode = true;
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (input != null) {
                input.close();
            }
        }
        return errorCode;
    }


    /**
     * 下载OSS图片转换为InputStream
     * @param key   图片路径
     * @param bucket  图片目录
     * @return
     * @throws Exception
     */
    public static InputStream getNormalPicObj(String key,String bucket) throws Exception{
        OSSObject object = client.getObject(bucket, key);
        InputStream objectContent = object.getObjectContent();
        return objectContent;
    }
    
}

FileUtil.java

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Base64;

/**
 * 文件工具类
 */
public class FileUtil {
    /**
     * 将文件转base64字符串
     * @param path
     * @return
     */
    public static  String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    /**
     * 将文件转base64字符串
     * @return
     */
    public static  String inputStreamToBase64(InputStream in) {
        String base64 = null;
        if (in == null) {
            return base64;
        }
        try {
            byte[] bytes = IOUtils.toByteArray(in);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }


    /**
     * 将文件转base64字符串
     * @param file
     * @return
     */
    public static  String fileToBase64(File file) {
        if(file == null){
            return null;
        }
        String base64 = null;
        InputStream in = null;
        try {
//            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    /**
     * BASE64解码成File文件
     * @param destPath
     * @param base64
     * @param fileName
     */
    public static File base64ToFile(String destPath,String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath=destPath;
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

}