二、阿里云OSS,AliossTemplate的封装使用

一、MINIO的安装,MinioTemplate的封装使用
二、阿里云OSS,AliossTemplate的封装使用
三、七牛云对象存储,QiniuTemplate的封装使用
四、华为云OBS对象存储,HwObsTemplate的封装使用
五、腾讯COS对象存储,TxCosTemplate的封装使用

二、阿里云OSS,AliossTemplate的封装使用

在上一章《一、MINIO的安装,MinioTemplate的封装使用》对MINIO进行可简单的介绍封装,阿里云OSS官方的文档是很详细的,这里同样基于MINIIO的思路,对桶的创建删除,文档的创建、删除、文件拷贝进行封装。这里不再对策略进行封装,可以在阿里云的官方控制台设置就好了。

1、购买服务

为了演示需要,花了4.9元购买了40个G的服务。

在这里插入图片描述

2、测试中的数据

详细的策略,官方也有相关的API对策略进行操作,我是个懒人,就没有阿里策略的代码封装,有时间再补上。

红框的地方是权限及策略配置的地方,很重要的,个人感觉比代码重要,要详细了解的。
在这里插入图片描述

3、Java代码封装AliossTemplate,操作阿里云oss

代码部分和《一、MINIO的安装,MinioTemplate的封装使用》高度的重合,这里仅贴出部分类的代码

3.1 引入依赖
<!--AliOSS-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <scope>provided</scope>
</dependency>
3.2 代码结构如下

在这里插入图片描述

3.3 MinioTemplate代码
package com.toto.core.oss;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetBucketPolicyResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.toto.core.oss.enums.PolicyType;
import com.toto.core.oss.enums.UploadType;
import com.toto.core.oss.model.TotoFile;
import com.toto.core.oss.tool.OssUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @Description: AliossTemplate
 * @Package: com.toto.core.oss
 * @Author gufanbiao
 * @CreateTime 2024-05-30 07:51
 */
@AllArgsConstructor
public class AliossTemplate implements OssTemplate {

    /** 阿里云客户端 */
    private final OSSClient ossClient;

    /** 配置类 */
    private final OssProperties ossProperties;

    @Override
    public void makeBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            ossClient.createBucket(bucketName);
        }
    }

    @Override
    public void deleteBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            ossClient.deleteBucket(bucketName);
        }
    }

    @Override
    public boolean bucketExists(String bucketName) {
        return ossClient.doesBucketExist(bucketName);
    }

    @Override
    public void copyFile(String bucketName, String fileName, String destBucketName) throws Exception {
        ossClient.copyObject(bucketName, fileName, destBucketName, fileName);
    }

    @Override
    public void copyFile(String bucketName, String fileName, String destBucketName, String destFileName) throws Exception {
        ossClient.copyObject(bucketName, fileName, destBucketName, destFileName);
    }

    @Override
    public TotoFile getFile(String fileName) throws Exception {
        return getFile(ossProperties.getBucketName(), fileName);
    }

    @Override
    public TotoFile getFile(String bucketName, String fileName) throws Exception {
        ObjectMetadata fileInfo = ossClient.getObjectMetadata(bucketName, fileName);
        TotoFile file = new TotoFile();
        file.setFileName(fileName);
        file.setFileUrl(fileUrl(file.getFileName()));
        file.setHash(fileInfo.getContentMD5());
        file.setFileSize(fileInfo.getContentLength());
        file.setUploadTime(fileInfo.getLastModified());
        file.setContentType(fileInfo.getContentType());
        return file;
    }

    @Override
    public String getPath(String fileName) {
        return getOssHost().concat("/").concat(fileName);
    }

    @Override
    public String getPath(String bucketName, String fileName) {
        return getOssHost(bucketName).concat("/").concat(fileName);
    }

    @Override
    public String fileUrl(String fileName) {
        return ossProperties.getEndpoint().concat("/").concat(ossProperties.getBucketName()).concat("/").concat(fileName);
    }

    @Override
    public String fileUrl(String bucketName, String fileName) {
        return ossProperties.getEndpoint().concat("/").concat(bucketName).concat("/").concat(fileName);
    }

    @Override
    public String getShortlytUrl(String bucketName, String fileName, Integer expires) throws Exception {
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName);
        request.setExpiration(new Date(System.currentTimeMillis() + expires * 60 * 1000)); // X分钟
        URL signedUrl = ossClient.generatePresignedUrl(request);
        return signedUrl.toString();
    }

    @Override
    public TotoFile putFile(MultipartFile file) throws Exception {
        return putFile(ossProperties.getBucketName(), file.getOriginalFilename(), file);
    }

    @Override
    public TotoFile putFile(String fileName, MultipartFile file) throws Exception {
        return putFile(ossProperties.getBucketName(), fileName, file);
    }

    @Override
    public TotoFile putFile(String bucketName, String fileName, MultipartFile file) throws Exception {
        return putFile(bucketName, fileName, file.getInputStream());
    }

    @Override
    public TotoFile putFile(String fileName, InputStream stream) throws Exception {
        return putFile(ossProperties.getBucketName(), fileName, stream);
    }

    @Override
    public TotoFile putFile(String bucketName, String fileName, InputStream stream) throws Exception {
        return putFile(bucketName, fileName, stream, "application/octet-stream", null);
    }

    @Override
    public TotoFile putFile(String bucketName, String fileName, InputStream stream, MultipartFile file) throws Exception {
        return putFile(bucketName, fileName, stream, "application/octet-stream", file);
    }

    private TotoFile putFile(String bucketName, String fileName, InputStream stream, String contentType, MultipartFile multipartFile) throws Exception {
        boolean cover = false;
        makeBucket(bucketName);
        String originalName = fileName;
        fileName = OssUtil.fileName(fileName);
        ossClient.putObject(bucketName, fileName, stream);
        TotoFile file = new TotoFile();
        file.setOriginalName(originalName);
        file.setFileName(fileName);
        file.setDomain(OssUtil.getOssHost(ossProperties,bucketName));
        file.setFileUrl(fileUrl(bucketName, fileName));
        file.setFileType(originalName.substring(originalName.lastIndexOf(".") + 1));
        file.setUploadType(UploadType.OSS.getType());
        if(ObjectUtil.isNotNull(multipartFile)){
            file.setFileSize(multipartFile.getSize());
            file.setContentType(multipartFile.getContentType());
            file.setUploadTime(new Date());
        }
        return file;
    }

    @Override
    public void deleteFile(String fileName) throws Exception {
        ossClient.deleteObject(ossProperties.getBucketName(), fileName);
    }

    @Override
    public void deleteFile(String bucketName, String fileName) throws Exception {
        ossClient.deleteObject(bucketName, fileName);
    }

    @Override
    public void deleteFiles(List<String> fileNames) throws Exception {
        for (String fileName:fileNames) {
            deleteFile(fileName);
        }
    }

    @Override
    public void deleteFiles(String bucketName, List<String> fileNames) throws Exception {
        for (String fileName:fileNames) {
            deleteFile(bucketName, fileName);
        }
    }

    public String getPolicyType(String bucketName, PolicyType policyType) {
        GetBucketPolicyResult bucketPolicy = ossClient.getBucketPolicy(bucketName);
        return bucketPolicy.getPolicyText();
    }

    /**
     * 获取域名
     * @param bucketName 存储桶名称
     * @return String
     */
    public String getOssHost(String bucketName) {
        String prefix = ossProperties.getEndpoint().contains("https://") ? "https://" : "http://";
        return prefix + bucketName + "." + ossProperties.getEndpoint().replaceFirst(prefix, "");
    }

    /**
     * 获取域名
     * @return String
     */
    public String getOssHost() {
        return getOssHost(ossProperties.getBucketName());
    }
}

3.4 AliOssTest 代码
package com.toto;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.toto.core.oss.AliossTemplate;
import com.toto.core.oss.OssProperties;
import com.toto.core.oss.model.TotoFile;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: AliOssTest
 * @Package: com.toto
 * @Author gufanbiao
 * @CreateTime 2024-05-31 07:56
 */
@SuppressWarnings("all")
public class AliOssTest {

    private static String ENDPOINT = "oss-cn-qingdao.aliyuncs.com";
    private static String ACCESS_KEY = "LTAI5tEbFZmBvmXXXXXXXXXX";
    private static String SECRET_KEY = "fmmjl5SNVmtE7r3OXXXXXXXXX";
    private static String BUCKET_NAME = "toto-test";
    private static String BUCKET_DEST_NAME = "toto-dest";

    public static AliossTemplate template() {
        // 创建配置类
        OssProperties ossProperties = new OssProperties();
        ossProperties.setEndpoint(ENDPOINT);
        ossProperties.setAccessKey(ACCESS_KEY);
        ossProperties.setSecretKey(SECRET_KEY);
        ossProperties.setBucketName(BUCKET_NAME);
        // 创建客户端
        OSS ossClient2 = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
        return new AliossTemplate(ossClient, ossProperties);
    }

    /*********************************** mock对象信息 *****************************************/
    private static String FILE_NAME = "你好世界.txt";
    private static String CONTENT_TYPE = "text/plain";
    private static String CONTENT = "你好世界!";
    /**
     * mock一个对象 使用Spring框架的MockMultipartFile类创建一个MultipartFile对象
     * @return
     * @throws IOException
     */
    public static MultipartFile createMultipartFile() throws IOException {
        return new MockMultipartFile(FILE_NAME, FILE_NAME, CONTENT_TYPE, CONTENT.getBytes());
    }

    /*********************************** 操作测试 *****************************************/
    /**
     * 创建 Bucket
     */
    @Test
    void testCreate() {
        template().makeBucket(BUCKET_NAME);
    }

    /**
     * 删除 Bucket,桶不存在报错
     */
    @Test
    void deleteBucket() {
        template().deleteBucket(BUCKET_NAME);
    }

    /**
     * 存储桶是否存在
     */
    @Test
    void bucketExists() {
        boolean b = template().bucketExists(BUCKET_NAME);
        System.out.println("存储桶是否存在:" + b);
    }

    /**
     * 上传文件 MultipartFile格式
     * {"fileName":"upload/2024-05-31/d130dbec79b8478cbc86e748315067d8.txt","originalName":"你好世界.txt","domain":"oss-cn-qingdao.aliyuncs.com/toto-test","uploadType":"0","fileType":"txt"}
     */
    @Test
    void putFile1() throws Exception {
        TotoFile totoFile = template().putFile(AliOssTest.createMultipartFile());
        System.out.println("上传文件对象封装:" + JSONObject.toJSON(totoFile));
    }

    /**
     * 上传文件 文件流模式
     */
    @Test
    void putFile2() throws Exception {
        InputStream inputStream = MinioTest.createMultipartFile().getInputStream();
        TotoFile totoFile = template().putFile(FILE_NAME, inputStream);
        System.out.println("上传文件对象封装:" + JSONObject.toJSON(totoFile));
    }

    /**
     * 上传文件 文件流模式
     */
    @Test
    void putFile3() throws Exception {
        TotoFile totoFile = template().putFile("hhhhhhh"+FILE_NAME, AliOssTest.createMultipartFile());
        System.out.println("上传文件对象封装:" + JSONObject.toJSON(totoFile));
    }

    /**
     * 文件复制到另一个桶(文件名/路径不变)
     * @throws Exception
     */
    @Test
    void copyFile1() throws Exception {
        template().copyFile(BUCKET_NAME,"upload/2024-05-31/432f69c3e04d4ad9a5d40a4b2fa4199b.txt",BUCKET_DEST_NAME);
    }

    /**
     * 文件复制到另一个桶(文件名/路径变更)
     * @throws Exception
     */
    @Test
    void copyFile2() throws Exception {
        template().copyFile(BUCKET_NAME,"upload/2024-05-31/432f69c3e04d4ad9a5d40a4b2fa4199b.txt",BUCKET_DEST_NAME,"upload/2024-06-01/76b4273da33a49649954bb5187bfedbe.txt");
    }

    /**
     * 获取文件信息
     * @throws Exception
     */
    @Test
    void statFile1() throws Exception {
        TotoFile totoFile = template().getFile("upload/2024-05-31/432f69c3e04d4ad9a5d40a4b2fa4199b.txt");
        System.out.println("获取文件对象信息:" + JSONObject.toJSONString(totoFile));
    }

    /**
     * 获取文件信息(指定桶的名称)
     * @throws Exception
     */
    @Test
    void statFile2() throws Exception {
        TotoFile totoFile = template().getFile(BUCKET_DEST_NAME,"upload/2024-05-31/432f69c3e04d4ad9a5d40a4b2fa4199b.txt");
        System.out.println("获取文件对象信息:" + JSONObject.toJSONString(totoFile));
    }

    /**
     * 获取文件路径信息(没有什么实质的参考,就是内部组装)
     */
    @Test
    void getPath1() {
        String path = template().getPath("upload/2024-05-31/432f69c3e04d4ad9a5d40a4b2fa4199b.txt");
        System.out.println("获取文件路径信息:" + path);
    }

    /**
     * 获取文件路径信息(没有什么实质的参考,就是内部组装)
     */
    @Test
    void getPath2() {
        String path = template().getPath(BUCKET_NAME,"upload/2024-05-26/5c88db26e57643de88591453e2385907.txt");
        System.out.println("获取文件路径信息:" + path);
    }

    /**
     * 获取文件路径信息(没有什么实质的参考,就是内部组装)
     */
    @Test
    void getFileUrl1(){
        String fileUrl = template().fileUrl("upload/2024-05-26/5c88db26e57643de88591453e2385907.txt");
        System.out.println("获取文件路径信息:" + fileUrl);
    }

    /**
     * 获取文件路径信息(没有什么实质的参考,就是内部组装)
     */
    @Test
    void getFileUrl2(){
        String fileUrl = template().fileUrl(BUCKET_NAME,"upload/2024-05-26/5c88db26e57643de88591453e2385907.txt");
        System.out.println("获取文件路径信息:" + fileUrl);
    }

    ///**
    // * https://www.alibabacloud.com/help/zh/oss/user-guide/common-examples-of-bucket-policy?spm=a2c63.p38356.0.0.3d392bdeHcqEnt
    // */
    //@Test
    //void getPolicyType() {
    //    String policyType = template().getPolicyType(BUCKET_NAME, null);
    //    System.out.println("获取当前桶的策略:" + policyType);
    //}

    /**
     * 删除文件,使用配置文件中的桶
     * @throws Exception
     */
    @Test
    void deleteFile1() throws Exception {
        template().deleteFile("upload/2024-05-31/d8a3827015254b34b2d12790ed683ba6.txt");
    }

    /**
     * 删除文件指定桶
     * @throws Exception
     */
    @Test
    void deleteFile2() throws Exception {
        template().deleteFile(BUCKET_NAME,"upload/2024-05-31/d130dbec79b8478cbc86e748315067d8.txt");
    }

    /**
     * 批量删除,默认配置文件中的桶(貌似有点问题,有时候可以,有时候不行)
     * @throws Exception
     */
    @Test
    void deleteFile3() throws Exception {
        List<String> fileNames = new ArrayList<>();
        fileNames.add("upload/2024-05-31/cfcae26f4cf340b498171131ce4269d0.txt");
        fileNames.add("upload/2024-05-31/c70820f9b48f4a46a2447bf07022a5ba.txt");
        template().deleteFiles(fileNames);
    }

    /**
     * 获取临时地址,临时地址使用在私有写中,才能达到想要的效果
     * @throws Exception
     */
    @Test
    void getShortlytUrl() throws Exception {
        String shortlytUrl = template().getShortlytUrl(BUCKET_NAME, "upload/2024-05-31/9e0bd17315594ef19448b4ead1df4cf8.txt", 5);
        System.out.println("文件临时地址" + shortlytUrl);
    }
}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grain322

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值