SpringBoot集成阿里云的对象存储

maven

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

yml中配置相关信息

oos:
  endpoint: oss-cn-beijing.aliyuncs.com
  keyid:     # 填写刚刚生成的AccessKey
  keysecret:   # 填写刚刚生成的Accesssecret
  bucketname:   # bucket名称
  filehost:      #bucket下文件夹的路径

写一个oosUtil

package com.study.utils.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.study.Exception.CustomException;
import com.study.utils.StringUtils;
import jdk.internal.util.xml.impl.Input;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
public class OosUtil {

    @Value("${oos.endpoint}")
    private String endpoint;

    @Value("${oos.keyid}")
    private String keyid;

    @Value("${oos.keysecret}")
    private String keysecret;

    @Value("${oos.bucketname}")
    private String bucketname;

    @Value("${oos.filehost}")
    private String filehost;


    //上传图片
    public String uploadImage(MultipartFile file) {
        
        String OriginFileName = file.getOriginalFilename();
        String subString = OriginFileName.substring(OriginFileName.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + subString;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile(inputStream, name);
        } catch (Exception e) {
            throw new CustomException("上传图片失败,请稍后再试");
        }

        return name;
    }

    private void uploadFile(InputStream inputStream,
                            String fileName) {

        String ret = "";
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endpoint, keyid, keysecret);
            PutObjectResult result = ossClient.putObject(bucketname, filehost + fileName, inputStream, objectMetadata);
            ret = result.getETag();
        } catch (Exception e) {
            throw new CustomException("上传图片失败,请稍后再试");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new CustomException("服务器异常,稍后再试");
                }
            }
        }
    }

    private String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension
                .equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        return "image/jpg";
    }

    /**
     * 获取图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            String url = this.getUrl(this.filehost + split[split.length - 1]);
            //                log.info(url);
            String[] spilt1 = url.split("\\?");
            return spilt1[0];
            //            return url;
        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, keyid, keysecret);
        URL url = ossClient.generatePresignedUrl(bucketname, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 单个图片上传
     *
     * @param file
     * @return
     */
    public String checkImage(MultipartFile file) {
        String fileUrl = uploadImage(file);
        String str = getImgUrl(fileUrl);
        return str.trim();
    }

}

调用

	@Autowired
    private OosUtil oosUtil;
    
    
    String URL = oosUtil.checkImage(file); //这是单个图片接口 返回的是保存在阿里云的图片地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值