阿里云对象存储OSS

  |   0 评论   |   0 浏览

一、阿里云对象存储OSS服务开通

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

image-20220102143729180

img

2、进入管理控制台

img

二、控制台使用

1、创建Bucket

命名:srb-file

读写权限:公共读

2、上传默认头像

创建文件夹avatar,上传默认的用户头像

img

三、使用RAM子用户

1、进入子用户管理页面

img

img

2、添加用户

img

3、获取子用户key

AccessKeyId, AccessKeySecret

4、设置用户权限

AliyunOSSFullAccess

image-20220102143643872

三、快速入门

1.创建maven工程

aliyun-oss

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

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.编写测试类

跟多api使用参考文档:https://help.aliyun.com/document_detail/145210.html

package com.llp.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.junit.Test;

import java.util.Date;

public class OSSTest {

    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    String endpoint = "oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    String accessKeyId = "你的accessKeyId";
    String accessKeySecret = "你的accessKeySecret";
    String bucketName = "你的bucketName";
	
    @Test
    public void testInit() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
	
    //创建bucket
    @Test
    public void testCreateBucketRequest() {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建CreateBucketRequest对象。
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);

        // 如果创建存储空间的同时需要指定存储类型和数据容灾类型, 请参考如下代码。
        // 此处以设置存储空间的存储类型为标准存储为例介绍。
        //createBucketRequest.setStorageClass(StorageClass.Standard);
        // 数据容灾类型默认为本地冗余存储,即DataRedundancyType.LRS。如果需要设置数据容灾类型为同城冗余存储,请设置为DataRedundancyType.ZRS。
        //createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
        // 设置存储空间的权限为公共读,默认为私有。
        //createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);

        // 创建存储空间。
        ossClient.createBucket(createBucketRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
	
    //判断bucket是否存在
    @Test
    public void testDoesBucketExist(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 判断存储空间examplebucket是否存在。如果返回值为true,则存储空间存在,否则存储空间不存在。
        boolean exists = ossClient.doesBucketExist(bucketName);
        System.out.println(exists);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

	//获取存储空间的地域:oss-cn-beijing
    @Test
    public void testGetBucketLocation(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String location = ossClient.getBucketLocation(bucketName);
        System.out.println(location);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
	
    //获取详情信息
    @Test
    public void testGetBucketInfo(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 存储空间的信息包括地域(Region或Location)、创建日期(CreationDate)、拥有者(Owner)等。
        // 填写Bucket名称,例如examplebucket。
        BucketInfo info = ossClient.getBucketInfo(bucketName);
        // 获取地域。
        String location = info.getBucket().getLocation();

        // 获取创建日期。
        Date creationDate = info.getBucket().getCreationDate();
        // 获取拥有者信息。
        Owner owner = info.getBucket().getOwner();
        // 获取容灾类型。
        DataRedundancyType dataRedundancyType = info.getDataRedundancyType();

        System.out.println(location);
        System.out.println(creationDate);
        System.out.println(owner);
        System.out.println(dataRedundancyType);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
	
    //设置bucket访问权限
    @Test
    public void testSetBucketAcl(){

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 设置存储空间的访问权限为私有。
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

}

四、项目中的使用

<!--lombok用来简化实体类:需要安装lombok插件-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <!--aliyunOSS-->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
    </dependency>

    <!-- 日期工具栏依赖 -->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>

    <!--让自定义的配置在application.yaml进行自动提示-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
aliyun:
  oss:
    endpoint: oss-cn-beijing.aliyuncs.com
    keyId: 你的accessKeyId
    keySecret: 你的accessKeySecret
    bucketName: 你的bucketName

配置类

@Data
@Component
@ConfigurationProperties("aliyun.oss")
public class OssProperties implements InitializingBean {

    private String endpoint;
    private String keyId;
    private String keySecret;
    private String bucketName;

    public static String ENDPOINT;
    public static String KEY_ID;
    public static String KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.ENDPOINT = endpoint;
        this.KEY_ID = keyId;
        this.KEY_SECRET = keySecret;
        this.BUCKET_NAME = bucketName;
    }

}

控制层

@Api(tags = "阿里云文件管理")
//@CrossOrigin //跨域
@RestController
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    /**
     * 文件上传
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(@ApiParam(value = "文件", required = true)
                    @RequestParam("file") MultipartFile file,

                    @ApiParam(value = "模块", required = true)
                    @RequestParam("module") String module) {
        try {
            String uploadUrl = fileService.upload(file.getInputStream(), module, file.getOriginalFilename());
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }

    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public R removeFile(@ApiParam(value = "文件地址",required = true)
                    @RequestParam("url") String url){
        fileService.removeFile(url);
        return R.ok().message("删除文件成功");
    }


}

文件的上传和文件的删除我们根据文件规则进行生成和删除即可

service

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        String bucketName = OssProperties.BUCKET_NAME;
        //判断存储空间是否存在
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            //不存在则创建
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            ossClient.createBucket(createBucketRequest);
        }
        //文件路径处理 llp/2021/12/25/uuid.jpg
        String folder = new DateTime().toString("/yyyy/MM/dd/");
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String filePath = module + folder + fileName;

        // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, filePath, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //阿里云文件绝对路径
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + filePath;
    }

    @Override
    public void removeFile(String url) {
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        //https://llp001.oss-cn-beijing.aliyuncs.com/test/2021/12/25/4dac5149-bd40-4a72-ab6c-569f97e194df.jpg
        //test/2021/12/25/4dac5149-bd40-4a72-ab6c-569f97e194df.jpg
        String host = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String objectName = url.substring(host.length());

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);

        // 删除文件或目录。如果要删除目录,目录必须为空。
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();

    }
}

标题:阿里云对象存储OSS
作者:llp
地址:https://llinp.cn/articles/2022/01/02/1641105914205.html