当前位置:网站首页>Alibaba cloud OSS - object storage service (tool)
Alibaba cloud OSS - object storage service (tool)
2022-06-26 10:46:00 【Slightly drunk CC】
Alibaba cloud OSS—— Object storage service ( Tools )
One 、 rely on
<!-- Alicloud file management service -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
Two 、yaml To configure
# Alibaba cloud OOS Service global configuration
aliyun:
oss:
#yourEndpoint Fill in Bucket The region corresponding to Endpoint. East China 1( Hangzhou ) For example ,Endpoint Fill in for https://oss-cn-hangzhou.aliyuncs.com.
end-point: your endpoint # You can also fill in your own domain name ( See the official website for details )
# Alicloud account AccessKey Have all the API Access rights of , The risk is high . It is highly recommended that you create and use it RAM The user carries out API Visit or daily operations , Please log in RAM Console creation RAM user .
accessKey-id: your accessKeyId
secret: your secret
# Storage space is what you use to store objects (Object) The container of , All objects must belong to a storage space .
bucket-name: your bucketName
3、 ... and 、OSS Tool class
notes : At present, only a single file upload has been completed 、 Batch file deletion , Other functions need to be improved …
/** * @Description * @Author cb * @Date 2022-01-06 11:25 **/
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class OSSUtils {
private String endPoint;
private String accessKeyId;
private String secret;
private String bucketName;
/** * Upload the local file to the directory of the target storage space * @param file Files to upload * @return Return the network path of the file */
public String uploadFileStream(MultipartFile file) {
//System.out.println(endPoint+"."+accessKeyId+"."+secret+"."+bucketName);
InputStream inputStream = null;
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secret);
// Get the stream from the uploaded file
try {
inputStream = file.getInputStream();
String oldName = file.getOriginalFilename();
int lastIndexOf = oldName.lastIndexOf(".");// Before the suffix . The index of
// Get the new filename ( original file name +UUID+ Suffix name )
String fileName= oldName.substring(0,lastIndexOf)+"-"+UUID.randomUUID().toString().replaceAll("-","")+oldName.substring(lastIndexOf);
// The directory structure of the file to be saved , It's like 20220102 Third level directory of
String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
fileName=dir+"/"+fileName;
// establish PutObjectRequest object .
// Fill in... In turn Bucket name ( for example examplebucket)、Object The full path ( for example exampledir/exampleobject.txt) And the full path of the local file .Object The full path cannot contain Bucket name .
// If no local path is specified , By default, the file is uploaded from the local path corresponding to the project to which the sample program belongs .
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
// If you need to upload, set the storage type and access permission , Please refer to the following example code .
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// Upload files .
ossClient.putObject(putObjectRequest);
// https://bucketName.endPoint/ Path to file ( Catalog + file name ),%s Is a placeholder for a string
String url=String.format("https://%s.%s/%s",bucketName,endPoint,fileName);
System.out.println(" Upload file path :"+url);
return url;
} catch (IOException e) {
throw new RuntimeException(" Failed to upload file ");
}finally {
if (null != ossClient){
// close OSSClient.
ossClient.shutdown();
}else if (null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/** * Delete files in bulk * 1. Fill in the full path of multiple files to be deleted . * 2. The file full path cannot contain Bucket name . Format :xxxDir/test.png or test.png * * @param fileWithPathList * @return Number of files deleted */
public Long deleteBatchObj(List<String> fileWithPathList){
Long count = 0L;
OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,secret);
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(fileWithPathList).withEncodingType("url"));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
for (String obj : deletedObjects) {
try {
String delObjStr = URLDecoder.decode(obj,"UTF-8");
System.out.println(delObjStr);// Output the deleted file name
count++;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if (null != ossClient){
ossClient.shutdown();
}
return count;
}
}
Four 、demo demonstration
4.1 SpringBoot Start class
@SpringBootApplication
@ComponentScan(basePackages = {
"com.ccbx.ymjr.base", "com.ccbx.ymjr.oss"})
public class OssServiceAp {
public static void main(String[] args) {
SpringApplication.run(OssServiceAp.class,args);
}
}
4.2 Controller Interface
/** * @Description * @Author cb * @Date 2022-01-06 11:59 **/
@RestController
@RequestMapping("/api/oos")
@Api(tags = " Operate Alibaba cloud OOS The interface to the server ")
public class OSSController {
@Autowired
private OSSUtils ossUtils;
@PostMapping("/upload")
@ApiOperation(" Upload files to OSS The server ")
public Result upload(MultipartFile file){
String url = ossUtils.uploadFileStream(file);
return Result.ok().data("url",url);
}
@PostMapping("/deleteBatchFile")
@ApiOperation(" Batch deletion OSS Files on the server ")
public Result deleteBatchFileFromOSS(@RequestBody List<String> filePathList){
try {
Long deleteCount = ossUtils.deleteBatchObj(filePathList);
return Result.ok().data("deleteCount",deleteCount);
} catch (Exception e) {
e.printStackTrace();
return Result.error().message(" Error deleting files in batch ");
}
}
}
4.3 swagger test
4.3.1 Upload test



4.3.2 Batch delete test


I'm looking at Bucket The file in has been deleted .
边栏推荐
- Pit record_ TreeSet custom sorting results in less data loss
- Concise course of probability theory and statistics in engineering mathematics second edition review outline
- MySQL 12th job - Application of stored procedure
- Redis (IV) redis association table caching
- OpenCV图像处理-灰度处理
- 挖财商学院证券开户安全嘛?
- 8-图文打造LeeCode算法宝典-最小栈与LRU缓存机制算法题解
- Global and Chinese markets of children's electronic thermometers 2022-2028: Research Report on technology, participants, trends, market size and share
- MySQL第十二次作业-存储过程的应用
- Opencv image processing - grayscale processing
猜你喜欢

Selection of webrtc video codec type VP8 H264 or other? (openh264 encoding, ffmpeg decoding)

Basic MySQL

【软件项目管理】期末复习知识点整理

See how I store integer data in the map < string, string > set

Developers, what is the microservice architecture?

AdaptiveAvgPool2D 不支持 onnx 导出,自定义一个类代替 AdaptiveAvgPool2D

MySQL 10th job - View

The sixth MySQL job - query data - multiple conditions

Omni channel, multi scenario and cross platform, how does app analyze channel traffic with data

MySQL第十四次作业--电子商城项目
随机推荐
Installer MySQL sous Linux [détails]
Notes - simple but adequate series_ KVM quick start
MySQL第六次作业-查询数据-多条件
【Leetcode】76. Minimum covering substring
Flutter and native communication (Part 1)
RDB persistence validation test
Redis中执行Lua脚本
Hcia-dhcp experiment
MySQL第十一作業-視圖的應用
MySQL 8th job
Global and Chinese market for baked potato chips 2022-2028: Research Report on technology, participants, trends, market size and share
String constant pool, class constant pool, and runtime constant pool
瑞萨电子面向物联网应用推出完整的智能传感器解决方案
SSH, SCP command appears permission denied, please try again solution
[echart] i. how to learn echart and its characteristic document reading notes
Concise course of probability theory and statistics in engineering mathematics second edition review outline
[untitled]
Global and Chinese markets in hair conditioner 2022-2028: Research Report on technology, participants, trends, market size and share
Adaptiveavgpool2d does not support onnx export. Customize a class to replace adaptiveavgpool2d
Global and Chinese market for change and configuration management software 2022-2028: Research Report on technology, participants, trends, market size and share