基于华为云OBS(对象存储服务)Java SDK开发初探

基于华为云OBS(对象存储服务)Java SDK开发初探

1.安装SDK

1.1Maven配置

<dependency>
 <groupId>com.huaweicloud</groupId>
 <artifactId>esdk-obs-java</artifactId>
 <version>3.19.7</version>
</dependency>

1.2gradle配置

api 'com.huaweicloud:esdk-obs-java:3.19.7'

2.OBS 桶操作

2.1工具类

  • 创建桶
  • 删除桶
  • 获取所有桶信息
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

public class ObsBucketOperation {
    @Value("${obs.endPoint}")
    private static String endPoint;

    @Value("${obs.ak}")
    private static String ak;

    @Value("${obs.sk}")
    private static String sk;

    private static final String bucketLocation = "cn-north-4";

    public static ObsClient getObsClient() {
        return new ObsClient(ak, sk, endPoint);
    }

    public void createBucket(String bucketName) throws IOException {
        ObsClient obsClient = getObsClient();
        ObsBucket obsBucket = new ObsBucket();
        obsBucket.setBucketName(bucketName);
        //设置桶的访问权限为公共读,默认是私有写
        obsBucket.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
        //设置桶的存储类型为归档存储
        obsBucket.setBucketStorageClass(StorageClassEnum.STANDARD);
        //设置桶区域位置
        obsBucket.setLocation(bucketLocation);
        //创建桶
        try {
            //创建成功
            HeaderResponse response = obsClient.createBucket(obsBucket);
            System.out.println(response.getRequestId());
        } catch (ObsException e) {
            //创建失败
            System.out.println("HTTP Code:" + e.getResponseCode());
            System.out.println("Error Code:" + e.getErrorCode());
            System.out.println("Error Message:" + e.getErrorMessage());
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            System.out.println();
        } finally {
            obsClient.close();
        }
    }

    public void getAllBucket() throws IOException {
        //创建ObsClient实例
        ObsClient obsClient = getObsClient();
        //获取列表
        ListBucketsRequest request = new ListBucketsRequest();
        request.setQueryLocation(true);
        List<ObsBucket> buckets = obsClient.listBuckets(request);
        for (ObsBucket bucket : buckets) {
            System.out.println("Bucket Name:" + bucket.getBucketName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("Create Date:" + bucket.getCreationDate());
            System.out.println("Location:" + bucket.getLocation());
            System.out.println();
        }
        obsClient.close();
    }

    public void removeBucket(String bucketName) throws IOException {
        ObsClient obsClient = getObsClient();
        boolean exist = obsClient.headBucket(bucketName);
        if (exist) {
            obsClient.deleteBucket(bucketName);
            obsClient.close();
        } else {
            System.out.println("Not exist:" + bucketName);
        }

    }
}

2.2测试类

package com.isscollege.utils;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.swing.*;
import java.io.IOException;

import static org.junit.Assert.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ObsBucketOperationTest {
    @Autowired
    private ObsBucketOperation obsBucketOperation;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }


    @Test
    public void testCreateBucket() throws IOException {
        String bucketName = JOptionPane.showInputDialog("Please input bucket name");
        obsBucketOperation.createBucket(bucketName);
        System.out.println("done!");
        System.exit(0);
    }

    @Test
    public void getAllBucket() throws IOException {
        obsBucketOperation.getAllBucket();
    }

    @Test
    public void removeBucket() throws IOException {
        String bucketName = JOptionPane.showInputDialog("Please input bucket name");
        obsBucketOperation.removeBucket(bucketName);
        System.out.println("done!");
        System.exit(0);
    }
}

3.OBS 对象操作

  • 上传对象
  • 删除对象
  • 下载对象
  • 预览流式对象
  • 获取所有对象信息

3.1工具类

package com.isscollege.utils;

import com.obs.services.ObsClient;
import com.obs.services.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
public class BucketObjectOperation {
    //从配置文件中读取授权信息
    @Value("${obs.endPoint}")
    private String endPoint;

    @Value("${obs.ak}")
    private String ak;

    @Value("${obs.sk}")
    private String sk;

    private String bucketName="obsBucketName";

    //获取OBS客户端实例
    public ObsClient getInstance() {
        return new ObsClient(ak, sk, endPoint);
    }

    //上传文件
    public Integer uploadFile(InputStream is, String objectKey) throws IOException {
        ObsClient obsClient = getInstance();
        Boolean flag = obsClient.doesObjectExist(bucketName, objectKey);
        PutObjectResult result = null;
        //同名文件可能被覆盖
        result = obsClient.putObject(bucketName, objectKey, is);
        //同名文件不会被覆盖
//        if (flag) {
//            return 0;
//        } else {
//            result = obsClient.putObject(bucketName, objectKey, is);
//        }
        obsClient.close();
        return result.getStatusCode();
    }

    public List<ObsObject> getAllFileInfo() throws IOException {
        ObsClient obsClient = getInstance();
        ObjectListing objectList = obsClient.listObjects(bucketName);
        List<ObsObject> list = objectList.getObjects();
        obsClient.close();
        return list;
    }

    public Boolean removeFile(String objectKey) throws IOException {
        ObsClient obsClient = getInstance();
        boolean exist = obsClient.doesObjectExist(bucketName, objectKey);
        DeleteObjectResult result = null;
        if (exist) {
            result = obsClient.deleteObject(bucketName, objectKey);
        }
        obsClient.close();
        return result.isDeleteMarker();//是否可以被标记为删除
    }

    //获取文件对象-下载
    public ObsObject getFile(String objectKey) {
        ObsClient obsClient = getInstance();
        boolean exist = obsClient.doesObjectExist(bucketName, objectKey);
        if (exist) {
            ObsObject object = obsClient.getObject(bucketName, objectKey);
            return object;
        }
        return null;
    }

    /**
     * 如果是流式文件,返回的链接可以在浏览器预览
     * 如果是非流式文件,返回的链接可以在浏览器里下载文件
     * @param objectKey
     * @return
     * @throws IOException
     */
    //预览授权访问-支持流式文件
    public String preview(String objectKey) throws IOException {
        ObsClient obsClient = getInstance();
        //300有效时间
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 300);
        request.setBucketName(bucketName);
        request.setObjectKey(objectKey);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        obsClient.close();
        return response.getSignedUrl();
    }
}

3.2测试类

import com.obs.services.model.ObsObject;
import com.obs.services.model.Owner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@SpringBootTest
@RunWith(SpringRunner.class)
public class BucketObjectOperationTest {
    @Autowired
    private BucketObjectOperation bucketObject;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void uploadFile() throws IOException {
        File file = new File("C:\\Users\\admin\\Pictures\\head.jpg");
        FileInputStream fis = new FileInputStream(file);
        String originalFileName = "head.jpg";
        String objectKey = UUID.randomUUID().toString().replace("-", "") + "_" + originalFileName;
        Integer integer = bucketObject.uploadFile(fis, objectKey);
        System.out.println("uploadFile:" + integer);
    }

    @Test
    public void getAllFileInfo() throws IOException {
        List<ObsObject> objectList = bucketObject.getAllFileInfo();
        for (ObsObject obsObject : objectList) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            System.out
                    .println("文件名:" + obsObject.getObjectKey() + "\t文件大小:" +
                            obsObject.getMetadata().getContentLength()
                            + "B\t上传时间:" + sdf.format(obsObject.getMetadata().getLastModified()));
        }
        System.out.println("65cb50a0aa0b4bf8bebde3d9121ff0cf".length());
    }

    @Test
    public void removeFile() throws IOException {
        bucketObject.removeFile("7b2ac4f756d9441095f8279b38862512校徽.jpg");
    }

    @Test
    public void getFile() throws IOException {
        ObsObject object = bucketObject.getFile("dc99d154f0c145088ca5d8511bdda385_head.jpg");
        if (object != null) {
            InputStream is = object.getObjectContent();
            FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\admin\\Desktop\\dc99d154f0c145088ca5d8511bdda385_head.jpg"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            System.out.println("done!");
            is.close();
            fos.close();
            return;
        }
        System.out.println("File not found!");
    }

    @Test
    public void preview() throws IOException {
        String url = bucketObject.preview("dc99d154f0c145088ca5d8511bdda385_head.jpg");
        System.out.println(url);
    }
}
  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
你可以使用 Java SDK 来实现华为云对象存储OBS的文件上传。以下是一个简单的示例代码: ```java import java.io.File; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.PutObjectResult; public class ObsUploadDemo { public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, ObsException, IOException { // 创建ObsClient对象 ObsClient obsClient = new ObsClient("yourAccessKeyId", "yourSecretAccessKey", "yourEndpoint"); // 设置bucket名称和对象名称 String bucketName = "yourBucketName"; String objectKey = "yourObjectName"; // 设置本地文件路径 String filePath = "yourLocalFilePath"; // 上传文件 File file = new File(filePath); PutObjectResult result = obsClient.putObject(bucketName, objectKey, file); // 打印上传结果 System.out.println("请求ID:" + result.getRequestId()); System.out.println("ETag:" + result.getEtag()); // 关闭ObsClient对象 obsClient.close(); } } ``` 其中,`yourAccessKeyId` 和 `yourSecretAccessKey` 分别是你的华为云账号的Access Key ID 和 Secret Access Key;`yourEndpoint` 是你的OBS服务的访问域名;`yourBucketName` 是你要上传的存储桶名称;`yourObjectName` 是你要上传的对象名称;`yourLocalFilePath` 是你要上传的本地文件路径。 注意,以上代码仅作为示例,实际使用时需要根据你的具体情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值