阿里云OSS云存储

it2023-08-22  67

一、对象存储OSS概述

为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。 OSS快速入门

二、使用流程

1、开通“对象存储OSS”服务

(1)申请阿里云账号 (2)实名认证 (3)开通“对象存储OSS”服务 (4)进入管理控制台

2、创建Bucket

3、获取操作的秘钥和id

OSS快速入门

3.1、创建Mavaen项目

3.2、引入pom

<dependencies> <!--aliyunOSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.8.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>

3.3、找到编码时需要用到的常量值

** (1)endpoint (2)bucketName (3)accessKeyId (4)accessKeySecret**

3.4、测试创建Bucket的连接

上传文件

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(); } }

3.5、判断存储空间是否存在

存储空间

@Test public void testExist() { // 创建OSSClient实例。 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); boolean exists = ossClient.doesBucketExist(bucketName); System.out.println(exists); // 关闭OSSClient。 ossClient.shutdown(); }

3.6、设置存储空间的访问权限

@Test public void testAccessControl() { // 创建OSSClient实例。 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // 设置存储空间的访问权限为:公共读。 ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); // 关闭OSSClient。 ossClient.shutdown(); }

4、操作流程

三、代码实现

配置pom.xml

<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>

启动类

package com.atguigu.oss;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude=DataSourceAutoConfiguration.class) @ComponentScan(basePackages = {"com.atguigu"}) public class OssApplication { public static void main(String[] args) { SpringApplication.run(OssApplication.class, args); }}

peoperties配置类

#服务端口 server.port=8002 #服务名 spring.application.name=service-oss #环境设置:dev、test、prod spring.profiles.active=dev #阿里云 OSS #不同的服务器,地址不同 aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com aliyun.oss.file.keyid=LTAI4FvvVEWiTJ3GNJJqJnk7 aliyun.oss.file.keysecret=9st82dv7EvFk9mTjYO1XXbM632fRbG #bucket可以在控制台创建,也可以使用java代码创建 aliyun.oss.file.bucketname=edu-guli-1010

Util—ConstantPropertiesUtils

创建常量读取工具类:ConstantPropertiesUtil.java 使用@Value读取application.properties里的配置内容 用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。

package com.atguigu.oss.utils; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; //当项目已启动,spring接口,spring加载之后,执行接口一个方法 @Component public class ConstantPropertiesUtils 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.bucketname}") private String bucketName; //定义公开静态常量 public static String END_POIND; public static String ACCESS_KEY_ID; public static String ACCESS_KEY_SECRET; public static String BUCKET_NAME; @Override public void afterPropertiesSet() throws Exception { END_POIND = endpoint; ACCESS_KEY_ID = keyId; ACCESS_KEY_SECRET = keySecret; BUCKET_NAME = bucketName; } }

service层—OssServiceImpl

参考SDK中的:Java->上传文件->简单上传->流式上传->上传文件流

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.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @Service public class OssServiceImpl implements OssService { //上传头像到oss @Override public String uploadFileAvatar(MultipartFile file) { // 工具类获取值 String endpoint = ConstantPropertiesUtils.END_POIND; String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; String bucketName = ConstantPropertiesUtils.BUCKET_NAME; try { // 创建OSS实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); //获取上传文件输入流 InputStream inputStream = file.getInputStream(); //获取文件名称 String fileName = file.getOriginalFilename(); //1 在文件名称里面添加随机唯一的值 String uuid = UUID.randomUUID().toString().replaceAll("-",""); // yuy76t5rew01.jpg fileName = uuid+fileName; //2 把文件按照日期进行分类 //获取当前日期 // 2019/11/12 String datePath = new DateTime().toString("yyyy/MM/dd"); //拼接 // 2019/11/12/ewtqr313401.jpg fileName = datePath+"/"+fileName; //调用oss方法实现上传 //第一个参数 Bucket名称 //第二个参数 上传到oss文件路径和文件名称 aa/bb/1.jpg //第三个参数 上传文件输入流 ossClient.putObject(bucketName,fileName , inputStream); // 关闭OSSClient。 ossClient.shutdown(); //把上传之后文件路径返回 //需要把上传到阿里云oss路径手动拼接出来 // https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg String url = "https://"+bucketName+"."+endpoint+"/"+fileName; return url; }catch(Exception e) { e.printStackTrace(); return null; } } }

OssController

package com.atguigu.oss.controller; import com.atguigu.commonutils.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; //上传头像的方法 @PostMapping public R uploadOssFile(MultipartFile file) { //获取上传文件 MultipartFile //返回上传到oss的路径 String url = ossService.uploadFileAvatar(file); return R.ok().data("url",url); } }
最新回复(0)