ruoyi引用阿里云oss上传文件

1、pom.xml引入依赖

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.17.4</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>sts20150401</artifactId>
            <version>1.1.4</version>
        </dependency>

2、创建方法类aliyunossUtil 

package com.ruoyi.common.utils.aliyun;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.TeaException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * 阿里云oss方法
 */
public class aliyunossUtil {


    private static String endpoint = "sts.cn-hangzhou.aliyuncs.com"; // sts 服务器地址
    private static String AccessKeyId = "***";
    private static String accessKeySecret = "***";
    private static String roleArn = "acs:ram::***:role/ossrole";
    private static String roleSessionName = "***";

    /**
     * @param endpoint    存储空间对应的地域域名
     * @param region      Endpoint对应地区,例如cn-hangzhou
     * @param bucketName  存储空间名称,例如examplebucket
     * @param inputStream 文件网络流
     * @param objectName  填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt
     * @param assumeRoleResponse  sts验证信息
     * @throws Exception
     */
    public static void upload(String endpoint, String region, String bucketName, InputStream inputStream, String objectName,AssumeRoleResponse assumeRoleResponse) throws Exception {
        //配置安全验证信息
        String accessKeyId = assumeRoleResponse.getBody().getCredentials().accessKeyId;
        String accessKeySecret = assumeRoleResponse.getBody().getCredentials().accessKeySecret;
        String securityToken = assumeRoleResponse.getBody().getCredentials().securityToken;
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret, securityToken);

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
           // PutObjectResult result = ossClient.putObject(putObjectRequest);
            //String add = result.getETag();
        } catch (OSSException oe) {
           throw oe;
        } catch (ClientException ce) {
           throw ce;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.sts20150401.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(AccessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        return new com.aliyun.sts20150401.Client(config);
    }

    /**
     * 使用sts获取验证信息
     * @return
     * @throws Exception
     */
    public static AssumeRoleResponse getAliyunSts() throws Exception {
        AssumeRoleResponse assumeRoleResponse = null;
        try {
            com.aliyun.sts20150401.Client client = createClient();
            com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                    .setDurationSeconds(3600L)
                    // .setPolicy("your_value")
                    .setRoleArn(roleArn)
                    .setRoleSessionName(roleSessionName);
            // 请求验证信息
            assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, new com.aliyun.teautil.models.RuntimeOptions());
            if (assumeRoleResponse != null && assumeRoleResponse.getStatusCode() != 200) {
                return null;
            }
        } catch (TeaException error) {
            throw error;
        } catch (Exception _error) {
            throw _error;
        }
        return assumeRoleResponse;
    }
}

3、调用上传方法

 String endpoint = "***";
 String bucketName = "***";
 String region = "***";
 String objectName = "files/" + filename;
 try {
     AssumeRoleResponse assumeRoleResponse = getStsCredentials();
     if (assumeRoleResponse == null) {
         logger.error("sts credentials为null");
     } else {
         aliyunossUtil.upload(endpoint, region, bucketName, inputStream, objectName, assumeRoleResponse);
     }
 } catch (Exception e) {
     e.printStackTrace();
 }

### RuoYi 框架 OSS 对象存储服务集成方法 #### 添加 MinIO 依赖 为了在 `ruoyi-common` 中支持 MinIO 的对象存储功能,在项目的 `pom.xml` 文件中添加如下依赖: ```xml <!-- Minio 文件存储 --> <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.2.1</version> </dependency> ``` 此操作引入了必要的库来处理与 MinIO 服务器之间的通信[^3]。 #### 修改配置文件 编辑 `application.yml` 或者相应的配置文件,加入 MinIO 连接参数设置: ```yaml spring: oss: type: minio # 设置为使用MinIO作为OSS提供方 endpoint: http://localhost:9000 # MinIO Server 地址 access-key: YOUR_ACCESS_KEY # 访问密钥 secret-key: YOUR_SECRET_KEY # 秘钥 bucket-name: your-bucket # 存储桶名称 ``` 这些属性定义了应用程序连接至 MinIO 实例所需的信息以及默认使用的存储桶名[^5]。 #### 启动 MinIO 服务 通过命令行启动 MinIO 服务实例,并指定数据目录和服务监听地址: ```bash minio.exe server D:\insurance_data_put --console-address ":9000" --address ":9005" ``` 这一步骤创建了一个运行中的 MinIO 节点并开放 API 接口供后续调用。 #### 编写业务逻辑代码 针对具体的应用场景编写上传下载等功能模块。下面是一个简单的 Java 方法示例外观模式下向 MinIO 发送文件的方式: ```java import io.minio.MinioClient; // ... 导入其他必要包 ... public class OssService { private final MinioClient client; public OssService(MinioClient client){ this.client = client; } /** * 将给定路径下的文件上传到指定bucket内. */ public void uploadFile(String filePath, String objectName) throws Exception{ try (InputStream inputStream = Files.newInputStream(Paths.get(filePath))) { PutObjectArgs args = PutObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(inputStream, -1, 10485760L) .contentType("application/octet-stream") // 自定义MIME类型 .build(); client.putObject(args); } } } ``` 上述代码展示了如何利用 MinIO SDK 完成基本的对象上传任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值