SpringBoot整合阿里云OSS对象存储服务的实现
今天来整合一下SpringBoot和阿里云OSS对象存储服务。
一、配置OSS服务
先在阿里云开通对象存储服务,拿到AccessKeyId、AccessKeySecret。
创建你的bucket(存储空间),相当于一个一个的文件夹目录。按业务需求分类存储你的文件,图片,音频,app包等等。创建bucket是要选择该bucket的权限,私有,公共读,公共读写,按需求选择。创建bucket时对应的endpoint要记住,上传文件需要用到。
可以配置bucket的生命周期,比如说某些文件有过期时间的,可以配置一下。
二、代码实现
引入依赖包
com.aliyun.oss aliyun-sdk-oss 2.8.3
配置文件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类
packagecom.example.file.config;
importlombok.Data;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="aliyun-oss")
@Data
publicclassAliyunOSSProperties{
/**
*服务器地点
*/
privateStringregion;
/**
*服务器地址
*/
privateStringendpoint;
/**
*OSS身份id
*/
privateStringaccessKeyId;
/**
*身份密钥
*/
privateStringaccessKeySecret;
/**
*App文件bucketName
*/
privateStringbucketApp;
/**
*App包文件地址前缀
*/
privateStringdomainApp;
}
上传文件工具类
packagecom.example.file.utils;
importcom.aliyun.oss.OSSClient;
importcom.aliyun.oss.OSSException;
importcom.aliyun.oss.model.ObjectMetadata;
importcom.aliyun.oss.model.PutObjectResult;
importcom.example.common.exception.BusinessErrorCode;
importcom.example.common.exception.BusinessException;
importcom.example.common.utils.FileIdUtils;
importcom.example.file.config.AliyunOSSProperties;
importcom.example.file.config.FileTypeEnum;
importorg.apache.commons.lang3.StringUtils;
importorg.apache.commons.lang3.Validate;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Component;
importorg.springframework.web.multipart.MultipartFile;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.ArrayList;
importjava.util.List;
@Component
publicclassAliyunOSSUtil{
@Autowired
privateAliyunOSSPropertiesaliyunOSSProperties;
privatestaticLoggerlogger=LoggerFactory.getLogger(AliyunOSSUtil.class);
/**
*文件不存在
*/
privatefinalStringNO_SUCH_KEY="NoSuchKey";
/**
*存储空间不存在
*/
privatefinalStringNO_SUCH_BUCKET="NoSuchBucket";
/**
*上传文件到阿里云OSS服务器
*
*@paramfiles
*@paramfileTypeEnum
*@parambucketName
*@paramstoragePath
*@return
*/
publicListuploadFile(MultipartFile[]files,FileTypeEnumfileTypeEnum,StringbucketName,StringstoragePath,Stringprefix){
//创建OSSClient实例
OSSClientossClient=newOSSClient(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getAccessKeyId(),aliyunOSSProperties.getAccessKeySecret());
ListfileIds=newArrayList<>();
try{
for(MultipartFilefile:files){
//创建一个唯一的文件名,类似于id,就是保存在OSS服务器上文件的文件名(自定义文件名)
StringfileName=FileIdUtils.creater(fileTypeEnum.getCode());
InputStreaminputStream=file.getInputStream();
ObjectMetadataobjectMetadata=newObjectMetadata();
//设置数据流里有多少个字节可以读取
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;
//上传文件
PutObjectResultresult=ossClient.putObject(bucketName,fileName,inputStream,objectMetadata);
logger.info("AliyunOSSAliyunOSSUtil.uploadFileToAliyunOSS,result:{}",result);
fileIds.add(prefix+fileName);
}
}catch(IOExceptione){
logger.error("AliyunOSSAliyunOSSUtil.uploadFileToAliyunOSSfail,reason:{}",e);
}finally{
ossClient.shutdown();
}
returnfileIds;
}
/**
*删除文件
*
*@paramfileName
*@parambucketName
*/
publicvoiddeleteFile(StringfileName,StringbucketName){
OSSClientossClient=newOSSClient(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getAccessKeyId(),aliyunOSSProperties.getAccessKeySecret());
ossClient.deleteObject(bucketName,fileName);
shutdown(ossClient);
}
/**
*根据图片全路径删除就图片
*
*@paramimgUrl图片全路径
*@parambucketName存储路径
*/
publicvoiddelImg(StringimgUrl,StringbucketName){
if(StringUtils.isBlank(imgUrl)){
return;
}
//问号
intindex=imgUrl.indexOf('?');
if(index!=-1){
imgUrl=imgUrl.substring(0,index);
}
intslashIndex=imgUrl.lastIndexOf('/');
StringfileId=imgUrl.substring(slashIndex+1);
OSSClientossClient=newOSSClient(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getAccessKeyId(),aliyunOSSProperties.getAccessKeySecret());
ossClient.deleteObject(bucketName,fileId);
shutdown(ossClient);
}
/**
*判断文件是否存在
*
*@paramfileName文件名称
*@parambucketName文件储存空间名称
*@returntrue:存在,false:不存在
*/
publicbooleandoesObjectExist(StringfileName,StringbucketName){
Validate.notEmpty(fileName,"fileNamecanbenotempty");
Validate.notEmpty(bucketName,"bucketNamecanbenotempty");
OSSClientossClient=newOSSClient(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getAccessKeyId(),aliyunOSSProperties.getAccessKeySecret());
try{
booleanfound=ossClient.doesObjectExist(bucketName,fileName);
returnfound;
}finally{
shutdown(ossClient);
}
}
/**
*复制文件
*
*@paramfileName源文件名称
*@parambucketName源储存空间名称
*@paramdestinationBucketName目标储存空间名称
*@paramdestinationObjectName目标文件名称
*/
publicvoidossCopyObject(StringfileName,StringbucketName,StringdestinationBucketName,StringdestinationObjectName){
Validate.notEmpty(fileName,"fileNamecanbenotempty");
Validate.notEmpty(bucketName,"bucketNamecanbenotempty");
Validate.notEmpty(destinationBucketName,"destinationBucketNamecanbenotempty");
Validate.notEmpty(destinationObjectName,"destinationObjectNamecanbenotempty");
OSSClientossClient=newOSSClient(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getAccessKeyId(),aliyunOSSProperties.getAccessKeySecret());
//拷贝文件。
try{
ossClient.copyObject(bucketName,fileName,destinationBucketName,destinationObjectName);
}catch(OSSExceptionoe){
logger.error("errorCode:{},Message:{},requestID:{}",oe.getErrorCode(),oe.getMessage(),oe.getRequestId());
if(oe.getErrorCode().equals(NO_SUCH_KEY)){
thrownewBusinessException(BusinessErrorCode.NO_SUCH_KEY);
}elseif(oe.getErrorCode().equals(NO_SUCH_BUCKET)){
thrownewBusinessException(BusinessErrorCode.NO_SUCH_BUCKET);
}else{
thrownewBusinessException(BusinessErrorCode.FAIL);
}
}finally{
shutdown(ossClient);
}
}
/**
*关闭oos
*
*@paramossClientossClient
*/
privatevoidshutdown(OSSClientossClient){
ossClient.shutdown();
}
}
文件类型枚举
packagecom.example.file.config;
publicenumFileTypeEnum{
IMG(1,"图片"),
AUDIO(2,"音频"),
VIDEO(3,"视频"),
APP(4,"App包"),
OTHER(5,"其他");
privateIntegercode;
privateStringmessage;
FileTypeEnum(Integercode,Stringmessage){
this.code=code;
this.message=message;
}
publicIntegergetCode(){
returncode;
}
publicStringgetMessage(){
returnmessage;
}
}
调用工具类上传文件
@Override publicListuploadImg(MultipartFile[]files){ if(files==null){ thrownewBusinessException(BusinessErrorCode.OPT_UPLOAD_FILE); } try{ returnaliyunOSSUtil.uploadFile(files,FileTypeEnum.IMG,aliyunOSSProperties.getBucketProduct(),null,aliyunOSSProperties.getDomainProduct()); }catch(Exceptione){ logger.error("uploadImgerrore:{}",e); thrownewBusinessException(BusinessErrorCode.UPLOAD_FAIL); } }
返回的List是文件上传之后文件的文件名集合。
到此就整合完成了。可以登录OSS控制台查看对应的文件。更多相关SpringBoot整合阿里云OSS内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。