aliyun图片存储OSS工具类

pom.xml配置jar包

 <!-- oss -->
 <dependency>
 
     <groupId>com.aliyun.oss</groupId>
     <artifactId>aliyun-sdk-oss</artifactId>
     <version>3.17.4</version>
 </dependency>

yml配置相关key

#oss 配置
oss:
  #AK
  accessKey: accessKey
  #SK
  secretKey: secretKey
  # 访问域名:以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com
  endpoint: https://oss-cn-hangzhou.aliyuncs.com
  # 存储空间:Bucket名称必须全局唯一
  bucketName: hsope-test
  #对象
  objectName: rental/

封装的OSSUtils

package com.db.common.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.db.common.utils.DateUtils;
import com.db.common.utils.uuid.UUID;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

@Component
public class OSSUtils {

    private static final Logger log = LoggerFactory.getLogger(OSSUtils.class);

    private static String accessKey;

    private static String secretKey;

    private static String endpoint;

    private static String bucketName;

    private static String objectName;

    @Value("${oss.accessKey}")
    public void setAccessKey(String accessKey) {
        OSSUtils.accessKey = accessKey;
    }

    @Value("${oss.secretKey}")
    public void setSecretKey(String secretKey) {
        OSSUtils.secretKey = secretKey;
    }

    @Value("${oss.endpoint}")
    public void setEndpoint(String endpoint) {
        OSSUtils.endpoint = endpoint;
    }

    @Value("${oss.bucketName}")
    public void setBucketName(String bucketName) {
        OSSUtils.bucketName = bucketName;
    }

    @Value("${oss.objectName}")
    public void setObjectNamee(String objectName) {
        OSSUtils.objectName = objectName;
    }

    //默认有效期10年
    private static final Long DEFAULT_EXPIRATION_TIME = 3600 * 1000 * 24 * 365 * 10L;

    private static OSS ossClient = null;

    public static void createClient() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
    }

    /**
     * 上传
     * @param inputStream 文件流
     * @param fileName 文件名
     */
    public static String upload(InputStream inputStream, String fileName) {
        if (ossClient == null) {
            createClient();
        }
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
        }
        ossClient.putObject(bucketName,  fileName, inputStream);
        log.info("文件上传成功:{}", fileName);
//        ossClient.shutdown();
        //获取url
        return getUrl(fileName);
    }

    /**
     * 下载
     * @param key key
     */
    public InputStream dowload(String key){
        if (ossClient == null) {
            createClient();
        }
        OSSObject object = ossClient.getObject(bucketName, key);
        return object.getObjectContent();
    }

    /**
     * 删除
     * @param key key
     */
    public void delete(String key){
        if (ossClient == null) {
            createClient();
        }
        ossClient.deleteObject(bucketName, key);
        log.info("文件删除成功:{}", key);
    }

    /**
     * 上传base64图片
     * @param base64 base64图片
     * @return url
     */
    public static String uploadBase64(String base64){
        //文件扩展名
        String fileExt = "jpeg";
        //base64照片,头部信息处理
        if (base64.contains(";base64,")) {
            base64 = base64.split(",")[1];
        }
        //获取日期
        String date = DateUtils.getNowShDate()+"/";
        String fileName = objectName + date + UUID.randomUUID().toString().replace("-","") + "." + fileExt;
        return upload(new ByteArrayInputStream(Base64.decodeBase64(base64)),fileName);
    }

    /**
     * 获取url
     */
    public static String getUrl(String fileName){
        if (ossClient == null) {
            createClient();
        }
        // 指定签名URL过期时间为10分钟。
        Date expiration = new Date(DateUtils.parseDate(DateUtils.getNowTime()).getTime() + DEFAULT_EXPIRATION_TIME );
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        if(url == null){
            log.info("文件上传失败:{}", fileName);
        }
        return "https://" + url.getHost() + url.getPath();
    }

    /**
     * 获取有时效的图片地址
     * @param imageUrl 例子
     * @return 图片地址
     */
    public static String getUrlByExpiration(String imageUrl) {
        if (ossClient == null) {
            createClient();
        }
        String fileName = objectName + imageUrl.split(objectName)[1];
        // 指定签名URL过期时间为10分钟。
        Date expiration = new Date(DateUtils.parseDate(DateUtils.getNowTime()).getTime() + 1000 * 60 * 10 );
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        return url == null ? null : url.toString();
    }
    /**
     * 根据有图片地址获取图片base64
     * @param filePath 图片地址
     * @return base64图片
     */
    public static String fileToBase64(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        return java.util.Base64.getEncoder().encodeToString(fileContent);
    }

    /**
     * 根据有时效的图片地址获取图片base64
     * @param imgFile 有时效的图片地址
     * @return base64图片
     */
    public static String getImgStr(String imgFile) {
        try {
            File tempFile = File.createTempFile("temp-", ".jpg");
            cn.hutool.http.HttpUtil.downloadFileFromUrl(imgFile,tempFile,3000);
            String base64str = fileToBase64(tempFile.getAbsolutePath());
            tempFile.delete();
            return base64str;
        } catch (Exception e) {
            e.printStackTrace();
            return "1";
        }
    }

    public static void main(String[] args) {
        OSSUtils ossUtils = new OSSUtils();
        String s = ossUtils.uploadBase64("");
        System.out.println("---------"+s);
    }
}

业务使用

存储

上传base64图片,获取到图片地址

OSSUtils.uploadBase64(f.getImage())

显示

根据存储的图片地址,获取到有时效的图片地址,给前端展示

OSSUtils.getUrlByExpiration(f.getImage()))

获取

根据存储的图片地址,获取base64图片

OSSUtils.getImgStr(OSSUtils.getUrlByExpiration(f.getImage()))

完结!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值