• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot整合阿里云OSS对象存储服务的实现

springboot 搞代码 4年前 (2022-01-09) 37次浏览 已收录 0个评论

今天来整合一下SpringBoot和阿里云OSS对象存储服务。

一、配置OSS服务

先在阿里云开通对象存储服务,拿到AccessKeyId、AccessKeySecret。

二、代码实现

引入依赖包

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

配置文件application.yml

aliyun-oss:
 #bucket名称
 bucketApp: xxx-app
 domainApp: https://xxx-app.oss-cn-shenzhen.aliyuncs.com/
 region: oss-cn-shenzhen
 endpoint : https://oss-cn-shenzhen.aliyuncs.com
 accessKeyId: 你的accessKeyId
 accessKeySecret: 你的accessKeySecret

对应上面配置文件的properties类

package com.example.file.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "aliyun-oss")
@Data
public class AliyunOSSProperties {

  /**
   * 服务器地点
   */
  private String region;
  /**
   * 服务器地址
   */
  private String endpoint;
  /**
   * OSS身份id
   */
  private String accessKeyId;
  /**
   * 身份密钥
   */
  private String accessKeySecret;

  /**
   * App文件bucketName
   */
  private String bucketApp;
  /**
   * App包文件地址前缀
   */
  private String domainApp;
}

上传文件工具类

package com.example.file.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.example.common.exception.BusinessErrorCode;
import com.example.common.exception.BusinessException;
import com.example.common.utils.FileIdUtils;
import com.example.file.config.AliyunOSSProperties;
import com.example.file.config.FileTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class AliyunOSSUtil {

  @Autowired
  private AliyunOSSProperties aliyunOSSProperties;

  private static Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

  /**
   * 文件不存在
   */
  private final String NO_SUCH_KEY = "NoSuchKey";
  /**
   * 存储空间不存在
   */
  private final String NO_SUCH_BUCKET = "NoSuchBucket";

  /**
   * 上传文件到阿里云 OSS 服务器
   *
   * @param files
   * @param fileTypeEnum
   * @param bucketName
   * @param storagePath
   * @return
   */
  public List<String> uploadFile(MultipartFile[] files, FileTypeEnum fileTypeEnum, String bucketName, String storagePath, String prefix) {
    //创建OSSClien<mark>本文来源gaodaimacom搞#代%码@网-</mark>t实例
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    List<String> fileIds = new ArrayList<>();
    try {
      for (MultipartFile file : files) {
      		//创建一个唯一的文件名,类似于id,就是保存在OSS服务器上文件的文件名(自定义文件名)
        String fileName = FileIdUtils.creater(fileTypeEnum.getCode());
        InputStream inputStream = file.getInputStream();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //设置数据流里有多少个字节可以读取
        objectMetadata.setContentLength(inputStream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        fileName = StringUtils.isNotBlank(storagePath) ? storagePath + "/" + fileName : fileName;
        //上传文件
        PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
        logger.info("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS,result:{}", result);
        fileIds.add(prefix + fileName);
      }
    } catch (IOException e) {
      logger.error("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS fail,reason:{}", e);
    } finally {
      ossClient.shutdown();
    }
    return fileIds;
  }

  /**
   * 删除文件
   *
   * @param fileName
   * @param bucketName
   */
  public void deleteFile(String fileName, String bucketName) {
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    ossClient.deleteObject(bucketName, fileName);
    shutdown(ossClient);
  }

  /**
   * 根据图片全路径删除就图片
   *
   * @param imgUrl   图片全路径
   * @param bucketName 存储路径
   */
  public void delImg(String imgUrl, String bucketName) {
    if (StringUtils.isBlank(imgUrl)) {
      return;
    }
    //问号
    int index = imgUrl.indexOf('?');
    if (index != -1) {
      imgUrl = imgUrl.substring(0, index);
    }
    int slashIndex = imgUrl.lastIndexOf('/');
    String fileId = imgUrl.substring(slashIndex + 1);
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    ossClient.deleteObject(bucketName, fileId);
    shutdown(ossClient);
  }

  /**
   * 判断文件是否存在
   *
   * @param fileName  文件名称
   * @param bucketName 文件储存空间名称
   * @return true:存在,false:不存在
   */
  public boolean doesObjectExist(String fileName, String bucketName) {
    Validate.notEmpty(fileName, "fileName can be not empty");
    Validate.notEmpty(bucketName, "bucketName can be not empty");
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    try {
      boolean found = ossClient.doesObjectExist(bucketName, fileName);
      return found;
    } finally {
      shutdown(ossClient);
    }

  }

  /**
   * 复制文件
   *
   * @param fileName       源文件名称
   * @param bucketName      源储存空间名称
   * @param destinationBucketName 目标储存空间名称
   * @param destinationObjectName 目标文件名称
   */
  public void ossCopyObject(String fileName, String bucketName, String destinationBucketName, String destinationObjectName) {
    Validate.notEmpty(fileName, "fileName can be not empty");
    Validate.notEmpty(bucketName, "bucketName can be not empty");
    Validate.notEmpty(destinationBucketName, "destinationBucketName can be not empty");
    Validate.notEmpty(destinationObjectName, "destinationObjectName can be not empty");
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    // 拷贝文件。
    try {
      ossClient.copyObject(bucketName, fileName, destinationBucketName, destinationObjectName);
    } catch (OSSException oe) {
      logger.error("errorCode:{},Message:{},requestID:{}", oe.getErrorCode(), oe.getMessage(), oe.getRequestId());
      if (oe.getErrorCode().equals(NO_SUCH_KEY)) {
        throw new BusinessException(BusinessErrorCode.NO_SUCH_KEY);
      } else if (oe.getErrorCode().equals(NO_SUCH_BUCKET)) {
        throw new BusinessException(BusinessErrorCode.NO_SUCH_BUCKET);
      } else {
        throw new BusinessException(BusinessErrorCode.FAIL);
      }
    } finally {
      shutdown(ossClient);
    }
  }

  /**
   * 关闭oos
   *
   * @param ossClient ossClient
   */
  private void shutdown(OSSClient ossClient) {
    ossClient.shutdown();
  }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot整合阿里云OSS对象存储服务的实现
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址