七牛雲OSSUtil

luyifo發表於2024-05-13

主要依賴

<!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
<dependency>
	<groupId>com.qiniu</groupId>
	<artifactId>qiniu-java-sdk</artifactId>
	<version>7.14.0</version>
</dependency>

<dependency>
	<groupId>com.alibaba.fastjson2</groupId>
	<artifactId>fastjson2</artifactId>
	<version>2.0.41</version>
</dependency>
public class QiNiuOssUtil {
	/*
	* 
	* */
    private static final String ACCESS_KEY = "*******";
    private static final String SECRET_KEY = "*******";
    private static final String DOMAIN = "******";
    private static final String BUCKET = "*****";

    public static String upload(byte[] bytes, String key) {
        return upload(new ByteArrayInputStream(bytes), key);
    }

    public static String upload(InputStream inputStream, String key) {
        Configuration cfg = new Configuration(Region.huanan());

        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String uploadToken = auth.uploadToken(BUCKET);
        try {
            Response response = uploadManager.put(inputStream, key, uploadToken, null, null);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return new DownloadUrl(DOMAIN, false, putRet.key).buildURL();
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上傳base64格式圖片
     * @param base64
     * @return
     */
    public static String uploadBase64Img(String base64) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(base64.substring(base64.indexOf(",") + 1));
        String suffix = base64.substring(base64.indexOf("/") + 1, base64.indexOf(";"));
        return upload(bytes, Md5.md5(bytes) + "." + suffix);
    }
}

相關文章