当前位置:网站首页>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
边栏推荐
- leetcode 剑指 Offer 48. 最长不含重复字符的子字符串
- OC-关于alloc和dealloc(还没开始写)
- 元宇宙改变人类工作模式的四种方式
- Beijing suddenly announced big news in the Metaverse
- Redis Desktop Manager 2022.4.2 released
- BERT预训练模型系列总结
- The use of qsort function and its analog implementation
- nacos实战项目中的配置
- A new generation of free open source terminal tool, so cool
- EViews 12.0软件安装包下载及安装教程
猜你喜欢

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

Redis Desktop Manager 2022.4.2 released

Re16:读论文 ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation

Re20:读论文的先例:普通法的信息理论分析

(C language) file operation

Test automation selenium (a)

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

Domino Server SSL Certificate Installation Guide

论文阅读:SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers

leetcode 剑指 Offer 47. 礼物的最大价值
随机推荐
flowable工作流所有业务概念
知识图谱之Cypher语言的使用
leetcode 剑指 Offer 57. 和为s的两个数字
MySQL |子查询
Study Notes 11--Direct Construction of Local Trajectories
Matplotlib--绘图标记
69. Sqrt(x)x 的平方根
Redis Desktop Manager 2022.4.2 released
唯物辩证法-条件论
Online target drone prompt.ml
debian10安装djando
Flask之路由(app.route)详解
再有人问你分布式事务,把这篇扔给他
[100个Solidity使用技巧]1、合约重入攻击
flyway的快速入门教程
606. 根据二叉树创建字符串(视频讲解!!!)
JCL 学习
Re18: Read the paper GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis
leetcode 剑指 Offer 12. 矩阵中的路径
(***重点***)Flink常见内存问题及调优指南(一)