四、华为云OBS对象存储,HwObsTemplate的封装使用

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

四、华为云OBS对象存储,HwObsTemplate的封装使用

在上一章《三、七牛云对象存储,AliossTemplate的封装使用》对七牛云对象存储进行可简单的介绍封装。本节对华为云对象存储同样基于MINIIO的思路,对桶的创建删除,文档的创建、删除、文件拷贝进行封装。

1、获取服务

华为云存储,没有赠送,需要真的花钱了o(╥﹏╥)o,不过也不贵。

在这里插入图片描述

测试的数据

在这里插入图片描述

2、Java代码封装HwObsTemplate,操作华为云对象存储
2.1 引入依赖
<dependency>
    <groupId>com.huaweicloud</groupId>
    <artifactId>esdk-obs-java</artifactId>
    <scope>provided</scope>
</dependency>
2.2 HwObsTemplate代码
package com.toto.core.oss;

import cn.hutool.core.util.ObjectUtil;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
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.util.Date;
import java.util.List;

/**
 * @Description: HwObsTemplate
 * @Package: com.toto.core.oss
 * @Author gufanbiao
 * @CreateTime 2024-06-01 15:28
 */
@SuppressWarnings("all")
@AllArgsConstructor
public class HwObsTemplate implements OssTemplate {

    private final ObsClient obsClient;
    private final OssProperties ossProperties;

    @Override
    public void makeBucket(String bucketName) throws Exception {
        if (!bucketExists(bucketName)) {
            obsClient.createBucket(bucketName,ossProperties.getRegion());
        }
    }

    @Override
    public void deleteBucket(String bucketName) throws Exception {
        obsClient.deleteBucket(bucketName);
    }

    @Override
    public boolean bucketExists(String bucketName) throws Exception {
        return obsClient.headBucket(bucketName);
    }

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

    @Override
    public void copyFile(String bucketName, String fileName, String destBucketName, String destFileName) throws Exception {
        obsClient.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 = obsClient.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) throws Exception {
        return getOssHost(ossProperties.getBucketName()).concat("/").concat(fileName);
    }

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

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

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

    @Override
    public String getShortlytUrl(String bucketName, String fileName, Integer expires) throws Exception {
        long expireSeconds = expires * 60;
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
        request.setBucketName(bucketName);
        request.setObjectKey(fileName);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }

    @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 {
        makeBucket(bucketName);
        String originalName = fileName;
        fileName = OssUtil.fileName(fileName);
        // 这里使用覆盖上传
        obsClient.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 {
        obsClient.deleteObject(ossProperties.getBucketName(), fileName);
    }

    @Override
    public void deleteFile(String bucketName, String fileName) throws Exception {
        obsClient.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);
        }
    }

    /**
     * 获取域名
     * @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 HwObsTest 代码
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.obs.services.ObsClient;
import com.toto.core.oss.AliossTemplate;
import com.toto.core.oss.HwObsTemplate;
import com.toto.core.oss.OssProperties;
import com.toto.core.oss.model.TotoFile;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
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: HwObsTest
 * @Package: com.toto
 * @Author gufanbiao
 * @CreateTime 2024-06-01 16:19
 */
@SuppressWarnings("all")
@SpringBootTest
public class HwObsTest {
    private static String ENDPOINT = "https://obs.cn-north-4.myhuaweicloud.com";
    private static String ACCESS_KEY = "IMUXO0UD8IXNEGDTEN3IBV";
    private static String SECRET_KEY = "6EbLx3FIkAMXhSQqPuiUrlTKTxluVCHqBXKdrf1LRv";
    private static String BUCKET_NAME = "toto-test";
    private static String BUCKET_DEST_NAME = "toto-dest";
    private static String REGION = "cn-north-4";

    public static HwObsTemplate template() {
        // 创建配置类
        OssProperties ossProperties = new OssProperties();
        ossProperties.setEndpoint(ENDPOINT);
        ossProperties.setAccessKey(ACCESS_KEY);
        ossProperties.setSecretKey(SECRET_KEY);
        ossProperties.setBucketName(BUCKET_NAME);
        ossProperties.setRegion(REGION);
        // 创建客户端
        ObsClient obsClient = new ObsClient(ACCESS_KEY, SECRET_KEY, ENDPOINT);
        return new HwObsTemplate(obsClient, 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() throws Exception {
        template().makeBucket(BUCKET_NAME);
    }

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

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

    /**
     * 上传文件 MultipartFile格式
     */
    @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-06-01/22ae08a9a7d44a088ff59297206c19c5.txt",BUCKET_DEST_NAME);
    }

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

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

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

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

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

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

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

    //@Test
    //void getPolicyType() throws Exception {
    //    String policyType = template().getPolicyType(BUCKET_NAME, null);
    //    System.out.println("获取当前桶的策略:" + policyType);
    //}

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

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

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

    /**
     * 获取临时地址,临时地址使用在私有写中,才能达到想要的效果
     * @throws Exception
     */
    @Test
    void getShortlytUrl() throws Exception {
        String shortlytUrl = template().getShortlytUrl(BUCKET_NAME, "upload/2024-06-01/3df80831cdb54aa78f39e89180602323.txt", 5);
        System.out.println("文件临时地址" + shortlytUrl);
    }
}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
华为云OBS提供了分段下载的功能,允许用户将大文件分成多个部分进行下载,从而提高下载效率并节省带宽和时间。华为云OBS分段下载的实现方式是通过HTTP协议的Range头信息来实现的。用户可以通过设置Range头信息中的起始位置和结束位置来指定需要下载的文件片段,服务器将只返回指定片段的数据给用户。 具体实现分段下载的方法如下: 1. 首先,你需要使用Java语言编写代码来实现华为云OBS文件的下载功能。你可以使用华为云OBSJava SDK来简化操作。可以参考中的Java华为云OBS文件上传下载工具类来实现下载功能。 2. 使用华为云OBSJava SDK,你可以通过设置GetObjectRequest对象的range属性来指定需要下载的文件片段的范围。例如,你可以设置range为"0-1023"表示只下载文件的前1024个字节,或者设置range为"1024-"表示从第1024个字节开始的所有数据。 3. 通过调用OBSClient的getObject方法并传入GetObjectRequest对象来发送下载请求。服务器将返回指定片段的数据给用户。 需要注意的是,华为云OBS分段下载功能需要服务器端支持,具体支持的范围大小可能会有限制。在使用分段下载功能时,建议参考华为云OBS的官方文档以了解更多详细信息和限制。 总结起来,华为云OBS提供了分段下载的功能,用户可以通过设置HTTP协议的Range头信息来指定需要下载的文件片段,服务器将只返回指定片段的数据给用户。使用Java语言可以通过华为云OBSJava SDK来实现分段下载功能。具体的实现方法可以参考中的Java华为云OBS文件上传下载工具类。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [图片批量上传至服务器/华为云obs 前台采用webuploader.js div+css布局 图片.zip华为云obs浏览器下载](https://blog.csdn.net/m0_54930214/article/details/127985386)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [华为云OBS文件上传下载工具类](https://blog.csdn.net/weixin_45285213/article/details/125596661)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [华为云obs参考代码以及demo](https://download.csdn.net/download/qq_38707432/10548349)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Grain322

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

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

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

打赏作者

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

抵扣说明:

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

余额充值