欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-15 09:54:09
今天来整合一下springboot和阿里云oss对象存储服务。一、配置oss服务先在阿里云开通对象存储服务,拿到accesskeyid、accesskeysecret。创建你的bucket(存储空间)...

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

一、配置oss服务

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

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

创建你的bucket(存储空间),相当于一个一个的文件夹目录。按业务需求分类存储你的文件,图片,音频,app包等等。创建bucket是要选择该bucket的权限,私有,公共读,公共读写,按需求选择。创建bucket时对应的endpoint要记住,上传文件需要用到。

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

可以配置bucket的生命周期,比如说某些文件有过期时间的,可以配置一下。

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

二、代码实现

引入依赖包

<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) {
    //创建ossclient实例
    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();
  }
}

文件类型枚举

package com.example.file.config;

public enum filetypeenum {

  img(1, "图片"),
  audio(2, "音频"),
  video(3, "视频"),
  app(4, "app包"),
  other(5, "其他");

  private integer code;
  private string message;

  filetypeenum(integer code, string message) {
    this.code = code;
    this.message = message;
  }

  public integer getcode() {
    return code;
  }

  public string getmessage() {
    return message;
  }

}

调用工具类上传文件

@override
  public list<string> uploadimg(multipartfile[] files) {
    if (files == null) {
      throw new businessexception(businesserrorcode.opt_upload_file);
    }
    try {
      return aliyunossutil.uploadfile(files, filetypeenum.img, aliyunossproperties.getbucketproduct(), null, aliyunossproperties.getdomainproduct());
    } catch (exception e) {
      logger.error("uploadimg error e:{}", e);
      throw new businessexception(businesserrorcode.upload_fail);
    }
  }

返回的list是文件上传之后文件的文件名集合。
到此就整合完成了。可以登录oss控制台查看对应的文件。更多相关springboot整合阿里云oss内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!