当前位置:网站首页>Alibaba Cloud OSS Object Storage
Alibaba Cloud OSS Object Storage
2022-07-30 10:14:00 【Fairy wants to carry】
目录
场景:利用阿里云OSS服务存储

测试
依赖导入
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>测试
Utilize keys and hell nodes andkey得到client
package com.atguigu.oss;
public class OSSTest {
// Endpoint以杭州为例,其它Region请按实际情况填写.
String endpoint = "your endpoint";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高.强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号.
String accessKeyId = "your accessKeyId";
String accessKeySecret = "your accessKeySecret";
String bucketName = "guli-file";
@Test
public void testCreateBucket() {
// 创建OSSClient实例.
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 创建存储空间.
ossClient.createBucket(bucketName);
// 关闭OSSClient.
ossClient.shutdown();
}
}设置存储空间的访问权限
@Test
public void testAccessControl() {
// 创建OSSClient实例.
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 设置存储空间的访问权限为:公共读.
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
// 关闭OSSClient.
ossClient.shutdown();
}项目集成OSS
准备工作

配置文件
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-fileOSS依赖导入
<dependencies>
<!-- 阿里云oss依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>启动项目
It should be noted here that we have not configured a data source,所以需要@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)Exclude data source configuration
package com.guli.oss;
@SpringBootApplication
@ComponentScan({"com.atguigu"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}Implement file avatar upload
1.创建常量读取工具类:ConstantPropertiesUtil——>作用:读取application.properties里的配置内容,实现spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用.
/**
* 常量类,读取配置文件application.properties中的配置
*/
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.filehost}")
private String fileHost;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FILE_HOST ;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
FILE_HOST = fileHost;
}
}2.文件上传接口
public interface FileService {
/**
* 文件上传至阿里云
* @param file
* @return
*/
String upload(MultipartFile file);
}3.File upload service implementation
思路:初始化OssClient,Then implement permission settings——>文件流+文件名称设置(组成uuid保证唯一性+时间进行分类)——>然后调用ossClient的api进行存储,Back to our unionoss的文件url
package com.atguigu.oss.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
/**
* 1.上传头像到Oss
* @param file
* @return
*/
@Override
public String uploadFileAvatar(MultipartFile file) {
//1.获取阿里云存储相关常量
String endPoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
//2.创建Oss实例
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
try {
//3.获取上传文件流
InputStream inputStream = file.getInputStream();
//4.获取文件名称
String fileName = file.getOriginalFilename();
/**
* 4.1Operates on file names,利用uuid生成唯一值,The purpose is to prevent the image from being overwritten
* 00820asjoa01.jpg
*/
String uuid= UUID.randomUUID().toString().replace("-","");
fileName=uuid+fileName;
/**
* 5.2把文件按照日期进行分类
* 1.获取当前路径
* 2.然后进行拼接
* https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
*/
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName=datePath+"/"+fileName;
/**
* 5.调用oss方法实现上传
* 第一个参数为bucket名称,The second is to upload tooss文件路径和文件名称,The third is the input stream
*/
ossClient.putObject(bucketName,fileName,inputStream);
//6.关闭OssClient
ossClient.shutdown();
/**
* 7.通过ossregular spliceurl
* https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
* https://edu-wyh.oss-cn-beijing.aliyuncs.com/01.png
*/
String url="https://"+bucketName+"."+endPoint+"/"+fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3.File upload control layer
package com.atguigu.oss.controller;
import com.atguigu.eduservice.R;
import com.atguigu.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
/**
* 1.上传头像
*/
@PostMapping
public R uploadOssFile(MultipartFile file){
//获取上传文件
//返回url头像路径
String url=ossService.uploadFileAvatar(file);
return R.ok().data("url",url);
}
}
Visit our path to get pictures
边栏推荐
- Detailed explanation of JVM memory layout, class loading mechanism and garbage collection mechanism
- (***重点***)Flink常见内存问题及调优指南(一)
- leetcode 剑指 Offer 47. 礼物的最大价值
- MySQL |子查询
- 分页 paging
- A near-perfect Unity full-platform hot update solution
- ESP32 入门篇(一)使用 VS Code 进行开发环境安装
- leetcode 剑指 Offer 52. 两个链表的第一个公共节点
- [100个Solidity使用技巧]1、合约重入攻击
- 唯物辩证法-条件论
猜你喜欢

Re18: Read the paper GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis

HR团队如何提升效率?人力资源RPA给你答案

idea2021+Activiti【最完整笔记一(基础使用)】

The use of qsort function and its analog implementation

在机器人行业的专业人士眼里,机器人行业目前的情况如何?

Domino服务器SSL证书安装指南

leetcode 剑指 Offer 15. 二进制中1的个数

Baidu promotion assistant encounters duplicate keywords, verification errors, how to delete redundant ones with one click

EViews 12.0 software installation package download and installation tutorial

leetcode 剑指 Offer 52. 两个链表的第一个公共节点
随机推荐
105. 从前序与中序遍历序列构造二叉树(视频讲解!!)
leetcode 剑指 Offer 57. 和为s的两个数字
hcip06 ospf special area comprehensive experiment
实战演练 | 在 MySQL 中计算每日平均日期或时间间隔
Redis Desktop Manager 2022.4.2 发布
BERT预训练模型系列总结
判断一颗树是否为完全二叉树——视频讲解!!!
MFCC转音频,效果不要太逗>V<!
[100个Solidity使用技巧]1、合约重入攻击
时刻铭记:总有一天你将破蛹而出
百度paddleocr检测训练
知识图谱之Cypher语言的使用
New in GNOME: Warn users when Secure Boot is disabled
mysql安装教程【安装版】
Detailed explanation of JVM memory layout, class loading mechanism and garbage collection mechanism
leetcode 剑指 Offer 12. 矩阵中的路径
在机器人行业的专业人士眼里,机器人行业目前的情况如何?
2022年顶会accepted papers list
If someone asks you about distributed transactions again, throw this to him
C语言顺序表基本操作