【华为云】SpringBoot + OBS 上传文件

一.引入Maven依赖

java 复制代码
 <dependency>
     <groupId>com.huaweicloud</groupId>
     <artifactId>esdk-obs-java</artifactId>
     <version>3.21.11</version>
 </dependency>

二.代码实现

java 复制代码
@Data
@Component
@RefreshScope
public class HuaWeiCloudObs {

    private static final Logger LOGGER = LoggerFactory.getLogger(HuaWeiCloudObs.class);

    @Value("${cloud.huawei.obs.accessKeyId}")
    private String AK;

    @Value("${cloud.huawei.obs.secretAccessKeyId}")
    private String SK;

    @Value("${cloud.huawei.obs.endPoint}")
    private String ENDPOINT;

    @Value("${cloud.huawei.obs.bucketName}")
    private String BUCKET_NAME;

    /**
     * OBS-上传文件
     *
     * @param objectKey 具体的文件名(含存储路径)
     * @param inputStream 输入流
     * @return PutObjectResult
     */
    public PutObjectResult uploadFile(String objectKey, InputStream inputStream) {
        ObsClient obsClient = null;
        PutObjectResult putObjectResult = null;
        try {
            obsClient = new ObsClient(AK, SK, ENDPOINT);
            putObjectResult = obsClient.putObject(BUCKET_NAME,objectKey, inputStream);
            LOGGER.info("上传文件PutObjectResult============" + putObjectResult);
        } catch (ObsException e) {
            printObsException(objectKey, e);
        } catch (Exception e) {
            LOGGER.error("OBS上传文件报错Exception===============" + e.getMessage());
        } finally {
            if (obsClient != null) {
                try {
                    // 关闭OBS连接
                    obsClient.close();
                } catch (IOException e) {
                    LOGGER.error("OBS关闭连接报错!===============" + e.getMessage());
                }
            }

        }
        return putObjectResult;
    }

    /**
     * OBS-上传文件
     *
     * @param objectKey 具体的文件名(含存储路径)
     * @param fileName 文件路径
     * @return PutObjectResult
     */
    public PutObjectResult uploadFile(String objectKey, String fileName) {
        ObsClient obsClient = null;
        PutObjectResult putObjectResult = null;
        try {
            obsClient = new ObsClient(AK, SK, ENDPOINT);
            putObjectResult = obsClient.putObject(BUCKET_NAME, objectKey, new File(fileName));
            LOGGER.info("上传文件PutObjectResult============" + putObjectResult);

        } catch (ObsException e) {
            printObsException(objectKey, e);
        } catch (Exception e) {
            LOGGER.error("OBS上传文件报错Exception===============" + e.getMessage());
        } finally {
            if (obsClient != null) {
                try {
                    // 关闭OBS连接
                    obsClient.close();
                } catch (IOException e) {
                    LOGGER.error("OBS关闭连接报错!===============" + e.getMessage());
                }
            }

        }
        return putObjectResult;
    }

    /**
     * OBS-下载文件(获取对象)
     *
     * @param objectKey 具体的文件名(含存储路径)
     * @return ObsObject
     */
    public ObsObject downloadFile(String objectKey) {

        ObsClient obsClient = null;
        ObsObject obsObject = null;

        try {

            obsClient = new ObsClient(AK, SK, ENDPOINT);
            obsObject = obsClient.getObject(BUCKET_NAME, objectKey);
            LOGGER.info("下载文件ObsObject============" + obsObject);

        } catch (ObsException e) {
            printObsException(objectKey, e);
        } catch (Exception e) {
            LOGGER.error("OBS下载文件报错Exception===============" + e.getMessage());
        } finally {

            if (obsClient != null) {
                try {
                    // 关闭OBS连接
                    obsClient.close();
                } catch (IOException e) {
                    LOGGER.error("OBS关闭连接报错!===============" + e.getMessage());
                }
            }

        }
        return obsObject;
    }

    /**
     * OBS-下载文件(流式下载)
     *
     * @param obsObject 下载文件信息
     * @return ByteArrayOutputStream
     */
    public static ByteArrayOutputStream convertOutputStream(ObsObject obsObject) {
        InputStream input = null;
        ByteArrayOutputStream bos = null;
        try {
            // 流式下载
            input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            bos = new ByteArrayOutputStream();
            int len;
            while ((len = input.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            LOGGER.info(new String(bos.toByteArray()));

            bos.close();
            input.close();

        } catch (Exception e) {
            LOGGER.error("OBS上传文件报错Exception===============" + e.getMessage());
        } finally {

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    LOGGER.error("bos关闭连接失败===============" + e.getMessage());
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    LOGGER.error("input关闭连接失败===============" + e.getMessage());
                }
            }

        }
        return bos;
    }

    /**
     * OBS-打印错误信息
     *
     * @param objectKey 路径KEY
     * @param e 错误信息
     * @param action 操作
     * @return ByteArrayOutputStream
     */
    private static void printObsException(String objectKey, ObsException e) {
        LOGGER.info("OBS文件报错ObsException===============" + objectKey);
        LOGGER.info("ObsException e: ====" + e);
        LOGGER.info("Response Code: ====" + e.getResponseCode());
        LOGGER.info("Error Message: ====" + e.getErrorMessage());
        LOGGER.info("Error Code: =======" + e.getErrorCode());
        LOGGER.info("Request ID: =======" + e.getErrorRequestId());
        LOGGER.info("Host ID: ==========" + e.getErrorHostId());
    }

三.注意

1.具体的配置参数 请到华为云OBS控制台创建获取

相关推荐
魔道不误砍柴功6 分钟前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2346 分钟前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨9 分钟前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
种树人2024081910 分钟前
如何在 Spring Boot 中启用定时任务
spring boot
测开小菜鸟2 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity3 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天3 小时前
java的threadlocal为何内存泄漏
java
caridle3 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^3 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋33 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx