阿里云OSS上传示例代码

引入maven架包


        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;

public class OSSUploader {
    //ndpoint:OSS服务的Endpoint。
    private static final String endpoint = "yourOSSEndpoint";
    //accessKeyId:OSS的Access Key ID。
    private static final String accessKeyId = "yourAccessKeyId";
    //accessKeySecret:OSS的Access Key Secret。
    private static final String accessKeySecret = "yourAccessKeySecret";
    //bucketName:要上传到的Bucket名称。
    private static final String bucketName = "yourBucketName";
    //
    private String roleArm;


	/***
    * 模拟OSS上传文件
    */
    public static void main(String[] args) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件
        //objectName:上传后的Object名称。
        String objectName = "yourObjectName";
        //filePath:要上传的文件路径。
        String filePath = "yourFilePath";
        File file = new File(filePath);
        PutObjectResult result = ossClient.putObject(bucketName, objectName, file);

        // 关闭OSSClient
        ossClient.shutdown();
    }
    
    /***
    * 获取前端上传需要的token
    */
	public String getOSSUpload() {
        Map<String, String> map = new HashMap<>();
        map.put("appKeyId", accessKeyId );
        map.put("appSecret", accessKeySecret );
        String stsToken = null;
        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        //roleSessionName时临时Token的会话名称,自己指定用于标识你的用户,或者用于区分Token颁发给谁
        //要注意roleSessionName的长度和规则,不要有空格,只能有'-'和'_'字母和数字等字符
        String roleSessionName = "sessiontest";
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:examplebucket/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        ProtocolType protocolType = ProtocolType.HTTPS;
        try {
            DefaultProfile.addEndpoint("", "cn-hangzhou", "Sts", endpoint);
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId , accessKeySecret );
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArm);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            request.setProtocol(protocolType);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            log.info("=============" + response.getCredentials().getAccessKeyId());
            log.info("=============" + response.getCredentials().getAccessKeySecret());
            log.info("=============" + response.getCredentials().getSecurityToken());
            stsToken = response.getCredentials().getSecurityToken();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return stsToken;
    }
    
	 /***
     * 获取OSS签名
     */
	public void getOSSSign() {
        Map<String, String> respMap = new LinkedHashMap<>();
        //host的格式为 bucketName.endpoint
        String host = "https://" + "videodis" + "." + endpoint ;
        //callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        String callbackUrl = "";
        String dir = ""; // 用户上传文件时指定的前缀。
        OSSClient client = new OSSClient(endpoint, accessKeyId , accessKeySecret);
        try {
            //设置过期时间为半小时1800L
            long expireTime = 60 * 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            java.sql.Date expiration = new java.sql.Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);
            respMap.put("bucket", "videodis");
            log.info("OSS结果:"+JSONObject.toJSONString(respMap));
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

	 /***
     * 获取OSS下载地址
     */
     public void getOSSDownloadUrl(String bucket, String key) {
        OSSClient client = new OSSClient(endpoint, accessKeyId , accessKeySecret );
        //判断文件是否存在
        // 设置URL过期时间为10年
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 10 * 365);
        // 生成URL
        URL url = client.generatePresignedUrl(bucket, key, expiration);
        client.shutdown();
        String s = url.toString().substring(0, url.toString().indexOf("?"));
        //生产环境中,OSS地址为内网地址,在此处转成外网地址
        if (s.contains("-internal")) {
            s = s.replace("-internal", "");
        }
        log.info(s);
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值