Commit c8663bd4 by jscat

nyx: 阿里云oss上传(视频+图片)逻辑

总体流程
1. 获取角色的授权accessid, getToken()
2. 通过授权accessid生成上传oss需要的参数, getOssParam()
parent 19a3c1d7
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
...@@ -171,6 +171,12 @@ ...@@ -171,6 +171,12 @@
<artifactId>aliyun-sdk-oss</artifactId> <artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version> <version>3.8.0</version>
</dependency> </dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
......
package cn.com.fun.nyxkey.api.service.impl; package cn.com.fun.nyxkey.api.service.impl;
...@@ -7,7 +7,12 @@ import cn.com.fun.nyxkey.api.repository.*; ...@@ -7,7 +7,12 @@ import cn.com.fun.nyxkey.api.repository.*;
import cn.com.fun.nyxkey.api.service.*; import cn.com.fun.nyxkey.api.service.*;
import cn.com.fun.nyxkey.api.domain.*; import cn.com.fun.nyxkey.api.domain.*;
import cn.com.fun.nyxkey.api.domain.query.*; import cn.com.fun.nyxkey.api.domain.query.*;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient; import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest; import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse; import com.aliyuncs.auth.sts.AssumeRoleResponse;
...@@ -18,6 +23,7 @@ import com.aliyuncs.profile.DefaultProfile; ...@@ -18,6 +23,7 @@ import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.profile.IClientProfile;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.K; import org.checkerframework.checker.units.qual.K;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -73,7 +79,23 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService { ...@@ -73,7 +79,23 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
@Value("${aliyun.oss.TokenExpireTime}") @Value("${aliyun.oss.TokenExpireTime}")
private int aliyunOssTokenExpireTime; private int aliyunOssTokenExpireTime;
@Value("${aliyun.oss.endpoint}")
private String aliyunOssEndpoint;
@Value("${aliyun.oss.bucket}")
private String aliyunOssBucket;
@Value("${aliyun.oss.callbackUrl}")
private String aliyunOssCallbackUrl;
@Value("${aliyun.oss.dir}")
private String aliyunOssDir;
/* /*
总体流程
1. 获取角色的授权accessid, getToken()
2. 通过授权accessid生成上传oss需要的参数, getOssParam()
接口api: 接口api:
STS临时授权访问OSS STS临时授权访问OSS
https://help.aliyun.com/document_detail/100624.html?spm=a2c4g.11186623.4.4.713b4c07v7XLf8 https://help.aliyun.com/document_detail/100624.html?spm=a2c4g.11186623.4.4.713b4c07v7XLf8
...@@ -83,19 +105,85 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService { ...@@ -83,19 +105,85 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
「OSS」阿里云OSS之STS临时访问授权 「OSS」阿里云OSS之STS临时访问授权
https://www.jianshu.com/p/a6047c5b3d3d https://www.jianshu.com/p/a6047c5b3d3d
「阿里云官方」在服务端通过Java代码完成签名,并且设置上传回调,然后通过表单直传数据到OSS
https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.15.526f6e28cqDt2n#concept-ahk-rfz-2fb
*/ */
public JSONResult Rockwell_ossServiceGetToken(String userName, String tokenName) public JSONResult Rockwell_ossServiceGetToken(String userName, String tokenName)
{ {
if (StringUtils.isBlank(userName) || StringUtils.isBlank(tokenName)) { Map<String, String> map = getSTSRoleAccessKeyId(userName, tokenName);
return new JSONResult(ExceptionMsg.OSSTokenNameIsBlack); return getToken(map);
}
//step2: 获取上传的参数
public JSONResult getToken(@org.jetbrains.annotations.NotNull Map<String, String> map)
{
//String accessId = aliyunOssAccessKeyID; // 请填写您的AccessKeyId。
String accessId = map.get("accessKeyId");
//String accessKey = aliyunOssAccessKeySecret; // 请填写您的AccessKeySecret。
String accessKey = map.get("accessKeySecret");
String endpoint = aliyunOssEndpoint; // 请填写您的 endpoint。
String bucket = aliyunOssBucket; // 请填写您的 bucketname 。
String host = "http://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
String callbackUrl = aliyunOssCallbackUrl;
String dir = aliyunOssDir; // 用户上传文件时指定的前缀。
OSSClient client = new OSSClient(endpoint, accessId, accessKey);
Map<String, String> respMap = new LinkedHashMap<String, String>();
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = client.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = client.calculatePostSignature(postPolicy);
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
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);
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
int totalCount = respMap.size();
JSONResult json = new JSONResult(totalCount,respMap);
return json;
} }
//step1: 获取STS临时授权的token
public Map<String, String> getSTSRoleAccessKeyId(String userName, String tokenName)
{
// if (StringUtils.isBlank(userName) || StringUtils.isBlank(tokenName)) {
// return new JSONResult(ExceptionMsg.OSSTokenNameIsBlack);
// }
Map<String,String> map = new HashMap<String,String>();
try { try {
// 获取临时授权token // 获取临时授权token
AssumeRoleResponse assumeRoleResponse = assumeRole(tokenName); AssumeRoleResponse assumeRoleResponse = assumeRole(tokenName);
// 构造返回参数 // 构造返回参数
Map<String,String> map = new HashMap<String,String>();
// 账号ID // 账号ID
map.put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId()); map.put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId());
// 密码 // 密码
...@@ -105,11 +193,12 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService { ...@@ -105,11 +193,12 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
// 有效时间 // 有效时间
map.put("expiration", assumeRoleResponse.getCredentials().getExpiration()); map.put("expiration", assumeRoleResponse.getCredentials().getExpiration());
return new JSONResult(1, map);
} catch (ClientException e) { } catch (ClientException e) {
e.printStackTrace(); e.printStackTrace();
return new JSONResult(ExceptionMsg.OSSServerInternalError, " 错误码:"+ e.getErrCode() + ";错误信息:" + e.getErrMsg()); //return map;
} }
return map;
} }
public AssumeRoleResponse assumeRole(String roleSessionName) throws ClientException { public AssumeRoleResponse assumeRole(String roleSessionName) throws ClientException {
...@@ -140,6 +229,7 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService { ...@@ -140,6 +229,7 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
return client.getAcsResponse(request); return client.getAcsResponse(request);
} }
public String readJson(String path) { public String readJson(String path) {
String filePath = "/config/" + path; String filePath = "/config/" + path;
InputStream inputStream = null; InputStream inputStream = null;
......
server: server:
...@@ -74,3 +74,7 @@ aliyun: ...@@ -74,3 +74,7 @@ aliyun:
RoleArn: acs:ram::1956317109339291:role/nyxtokengeneratorrolepolicy RoleArn: acs:ram::1956317109339291:role/nyxtokengeneratorrolepolicy
PolicyFile: policy/bucket_full_access_policy.txt PolicyFile: policy/bucket_full_access_policy.txt
TokenExpireTime: 30 TokenExpireTime: 30
endpoint: oss-cn-hangzhou.aliyuncs.com
bucket: 930-test-sh
callbackUrl: http://88.88.88.88:8888
dir: user-dir/
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论