前言
阿里雲對象存儲服務(Object Storage Service,簡稱 OSS),是阿里雲提供的海量、安全、低成本、高可靠的雲存儲服務。其數據設計持久性不低於 99.9999999999%(12 個 9),服務設計可用性(或業務連續性)不低於 99.995%。
OSS 具有與平臺無關的 RESTful API 接口,您可以在任何應用、任何時間、任何地點存儲和訪問任意類型的數據。
您可以使用阿里雲提供的 API、SDK 接口或者 OSS 遷移工具輕鬆地將海量數據移入或移出阿里雲 OSS。數據存儲到阿里雲 OSS 以後,您可以選擇標準存儲(Standard)作為移動應用、大型網站、圖片分享或熱點音視頻的主要存儲方式,也可以選擇成本更低、存儲期限更長的低頻訪問存儲(Infrequent Access)和歸檔存儲(Archive)作為不經常訪問數據的存儲方式。
登錄阿里雲,進入到控制檯
點擊確定,就建好了。
- 接下來就開始附代碼
新建一個springboot項目
導入依賴 pom.xml
<code><
project
xmlns
="http://maven.apache.org/POM/4.0.0"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
><
modelVersion
>4.0.0modelVersion
><
groupId
>org.examplegroupId
><
artifactId
>SpringOOSartifactId
><
version
>1.0-SNAPSHOTversion
><
dependencies
><
dependency
><
groupId
>org.springframework.bootgroupId
><
artifactId
>spring-boot-starter-webartifactId
><
version
>2.3.0.RELEASEversion
>dependency
><
dependency
><
groupId
>org.springframework.bootgroupId
><
artifactId
>spring-boot-starter-testartifactId
><
scope
>testscope
><
version
>2.3.0.RELEASEversion
>dependency
><
dependency
><
groupId
>com.aliyun.ossgroupId
><
artifactId
>aliyun-sdk-ossartifactId
><
version
>3.4.2version
>dependency
><
dependency
><
groupId
>org.projectlombokgroupId
><
artifactId
>lombokartifactId
><
version
>1.18.4version
><
scope
>providedscope
>dependency
><
dependency
><
groupId
>joda-timegroupId
><
artifactId
>joda-timeartifactId
><
version
>2.9.9version
>dependency
><
dependency
><
groupId
>org.apache.commonsgroupId
><
artifactId
>commons-lang3artifactId
><
version
> 3.8.1version
>dependency
>dependencies
>project
> /<code>
application.yml
<code>oss:
endpoint:
oss-cn-shenzhen.aliyuncs.com
url:
https://oos-all.oss-cn-shenzhen.aliyuncs.com/
accessKeyId:
accessKeySecret:
bucketName:
/<code>
寫一個config配置類
<code>package
com.sykj.config;import
lombok.Data;import
org.springframework.beans.factory.annotation
.Value;import
org.springframework.context.annotation
.Configuration;import
java.io.Serializable;public
class
OSSConfig
implements
Serializable
{private
staticfinal
long serialVersionUID = -119396871324982279L
;private
String endpoint;private
String url;private
String accessKeyId;private
String accessKeySecret;private
String bucketName; } /<code>
工具類
<code>package
com.sykj.util;import
com.aliyun.oss.ClientConfiguration;import
com.aliyun.oss.OSSClient;import
com.aliyun.oss.common.auth.DefaultCredentialProvider;import
com.aliyun.oss.model.ObjectMetadata;import
com.sykj.config.OSSConfig;import
org.springframework.web.multipart.MultipartFile;import
java.io.IOException;import
java.util.UUID;public
class
OSSBootUtil
{private
OSSBootUtil
()
{}private
volatile
static
OSSClient ossClient =null
;public
static
Stringupload
(OSSConfig ossConfig, MultipartFile file, String fileDir)
{ initOSS(ossConfig); StringBuilder fileUrl =new
StringBuilder();try
{ String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'
)); String fileName = System.currentTimeMillis() +"-"
+ UUID.randomUUID().toString().substring(0
,18
) + suffix;if
(!fileDir.endsWith("/"
)) { fileDir = fileDir.concat("/"
); } fileUrl = fileUrl.append(fileDir + fileName); System.out.println(fileUrl+"-----------------"
); ObjectMetadata objectMetadata =new
ObjectMetadata(); objectMetadata.setContentType("image/jpg"
); ossClient.putObject(ossConfig.getBucketName(), fileUrl.toString(), file.getInputStream(),objectMetadata); }catch
(IOException e) { e.printStackTrace();return
null
; } fileUrl = fileUrl.insert(0
,ossConfig.getUrl());return
fileUrl.toString(); }private
static
OSSClientinitOSS
(OSSConfig ossConfig)
{if
(ossClient ==null
) {synchronized
(OSSBootUtil.
class
) {if
(ossClient ==null
) { ossClient =new
OSSClient(ossConfig.getEndpoint(),new
DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()),new
ClientConfiguration()); } } }return
ossClient; }public
static
ResponseResultdelete
(String objectName,OSSConfig ossConfig)
{ initOSS(ossConfig); String fileName = objectName.replace("https://oos-all.oss-cn-shenzhen.aliyuncs.com/"
,""
); System.out.println(fileName+"******************************"
); ossClient.deleteObject(ossConfig.getBucketName(), fileName);return
ResponseResult.ok("刪除成功"
,fileName); } } /<code>
數據返回工具類
<code>package
com.sykj.util;import
lombok.AllArgsConstructor;import
lombok.Data;import
lombok.NoArgsConstructor;import
java.io.Serializable;public
class
ResponseResult
implements
Serializable
{private
Integer code;private
String message;private
Object object;public
static
ResponseResultok
(String message)
{return
new
ResponseResult(200
,message,null
); }public
static
ResponseResultok
(String message, Object object)
{return
new
ResponseResult(200
,message,object); }public
static
ResponseResulterror
(String message)
{return
new
ResponseResult(500
,message,null
); }public
static
ResponseResulterror
(String message, Object o)
{return
new
ResponseResult(500
,message,o); } } /<code>
Service類
<code>package
com.sykj.service;import
com.sykj.util.ResponseResult;import
org.springframework.http.ResponseEntity;import
org.springframework.web.multipart.MultipartFile;public
interface
CommonService
{ResponseResult
uploadOSS
(MultipartFile file)
throws
Exception;ResponseResult
delete
(String objectName)
; } /<code>
Service實現類
<code>package
com.sykj.service.impl;import
com.sykj.config.OSSConfig;import
com.sykj.service.CommonService;import
com.sykj.util.OSSBootUtil;import
com.sykj.util.ResponseResult;import
org.springframework.beans.factory.annotation.Autowired;import
org.springframework.http.HttpHeaders;import
org.springframework.http.HttpStatus;import
org.springframework.http.MediaType;import
org.springframework.http.ResponseEntity;import
org.springframework.stereotype.Service;import
org.springframework.web.multipart.MultipartFile;import
java.text.SimpleDateFormat;import
java.util.Date;import
java.util.HashMap;import
java.util.Map; ("commonService"
)public
class
CommonServiceImpl
implements
CommonService
{private
OSSConfig ossConfig;public
ResponseResultuploadOSS
(MultipartFile file)
throws
Exception { SimpleDateFormat simpleDateFormat=new
SimpleDateFormat("yyyy-MM-dd"
); String format = simpleDateFormat.format(new
Date()); String ossFileUrlBoot =null
; ossFileUrlBoot = OSSBootUtil.upload(ossConfig, file,"jpc/"
+format); System.out.println(ossFileUrlBoot); Map resultMap =new
HashMap<>(16
); resultMap.put("ossFileUrlBoot"
, ossFileUrlBoot);return
ResponseResult.ok("上傳成功~~"
,ossFileUrlBoot); }public
ResponseResultdelete
(String objectName)
{ ResponseResult delete = OSSBootUtil.delete(objectName, ossConfig);return
delete; } } /<code>
Controller類
<code>package
com.sykj.comtroller;import
com.sun.org.apache.regexp.internal
.RE;import
com.sykj.service.CommonService;import
com.sykj.util.ResponseResult;import
org.slf4j.Logger;import
org.slf4j.LoggerFactory;import
org.springframework.beans.factory.annotation
.Autowired;import
org.springframework.http.HttpHeaders;import
org.springframework.http.HttpStatus;import
org.springframework.http.MediaType;import
org.springframework.http.ResponseEntity;import
org.springframework.web.bind.annotation
.RequestMapping;import
org.springframework.web.bind.annotation
.RequestMethod;import
org.springframework.web.bind.annotation
.RequestParam;import
org.springframework.web.bind.annotation
.RestController;import
org.springframework.web.multipart.MultipartFile;public
class
CommonController
{private
staticfinal
Logger logger = LoggerFactory.getLogger(CommonController.
class
);private
CommonService commonService;public
ResponseResult uploadOSS( MultipartFile file) throws Exception { System.out
.println(file.getInputStream());return
ResponseResult.ok("ok"
); }public
ResponseResult deltetOss(String objectName){ System.out
.println(objectName+"-------------------------------"
); ResponseResult delete = commonService.delete(objectName);return
delete; } } /<code>
注意postman選擇file
這樣就完成了
最後
感謝你看到這裡,看完有什麼的不懂的可以在評論區問我,覺得文章對你有幫助的話記得給我點個贊,每天都會分享java相關技術文章或行業資訊,歡迎大家關注和轉發文章!