当前位置:网站首页>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
边栏推荐
- EViews 12.0软件安装包下载及安装教程
- 【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
- JCL 学习
- Day113. Shangyitong: WeChat login QR code, login callback interface
- [100个Solidity使用技巧]1、合约重入攻击
- 神秘的APT攻击
- leetcode 剑指 Offer 15. 二进制中1的个数
- Always remember: one day you will emerge from the chrysalis
- Re21:读论文 MSJudge Legal Judgment Prediction with Multi-Stage Case Representation Learning in the Real
- spark udf 接受并处理 null值.
猜你喜欢

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

Test automation selenium (a)

国外资源加速下载器,代码全部开源

线程池方式开启线程--submit()和execute()的区别

The thread pool method opens the thread -- the difference between submit() and execute()

(Text) Frameless button settings
![idea2021+Activiti [the most complete note one (basic use)]](/img/60/55cccf257523bed2c8829361cea97c.png)
idea2021+Activiti [the most complete note one (basic use)]

快解析结合友加畅捷通t1飞跃版

leetcode 剑指 Offer 47. 礼物的最大价值
容器技术 -- 简单了解 Kubernetes 的对象
随机推荐
梅科尔工作室-看鸿蒙设备开发实战笔记五——驱动子系统开发
leetcode 剑指 Offer 25. 合并两个排序的链表
Baidu promotion assistant encounters duplicate keywords, verification errors, how to delete redundant ones with one click
Meikle Studio-Look at the actual combat notes of Hongmeng device development six-wireless networking development
EViews 12.0 software installation package download and installation tutorial
(BUG记录)No module named PIL
nacos实战项目中的配置
Test automation selenium (a)
debian10 install djando
唯物辩证法-条件论
shell script
A new generation of free open source terminal tool, so cool
快解析结合任我行crm
Re19:读论文 Paragraph-level Rationale Extraction through Regularization: A case study on European Court
PyQt5-用像素点绘制正弦曲线
The thread pool method opens the thread -- the difference between submit() and execute()
leetcode 剑指 Offer 58 - I. 翻转单词顺序
Determine whether a tree is a complete binary tree - video explanation!!!
Materialist Dialectics - Conditionalism
Do you really understand the 5 basic data structures of Redis?