Springboot定义阿里云oss工具类

Springboot定义阿里云oss工具类


文章目录

1、定义OSS相关配置

首先,在 application.yml 文件中定义阿里云 OSS 的相关配置信息。这些配置包括 endpointaccess-key-idaccess-key-secretbucket-name

yml 复制代码
alioss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    access-key-id: you_key_id
    access-key-secret: you_key_secret
    bucket-name: your_bucket_name
2、读取OSS配置

接下来,创建一个 AliOssProperties 类,用于读取 application.yml 中的配置。

java 复制代码
@Component
@ConfigurationProperties(prefix = "oss.alioss")
@Data
public class AliOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

}
3、生成OSS工具类对象

为了生成 OSS 工具类对象,我们需要创建一个配置类 OssConfiguration,并在其中定义一个 AliOssUtil 的 Bean。

java 复制代码
/**
 * 配置类,用于创建AliOssUtil对象
 */
@Configuration
@Slf4j
public class OssConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName());
    }
}
4、定义使用工具类

最后,定义 AliOssUtil 工具类,实现文件上传功能。

java 复制代码
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

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

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}
相关推荐
陈随易5 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
IT界的老黄牛6 小时前
Spring Boot 的 `/actuator/health` 不是免费的:健康检查打爆连接池的反面教材
spring boot·hikaricp·actuator·健康检查·线上排障·架构反模式
凌虚8 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
IT_陈寒9 小时前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端
前端开发张小七9 小时前
Java 学习笔记 · 第一课:基础语法与核心概念
java·后端
海盗12349 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
沙湖遇雨9 小时前
6. Pipeline 的生命周期
后端
青青子衿悠悠我心10 小时前
TRAE Work让财务月底对账3小时变5分钟
后端
创安电气研究所10 小时前
用TypeScript给Modbus设备做一层适配器
后端
妙码生花10 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十):增加管理员角色组管理
前端·后端·ai编程