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();
 }

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐