一、后端加密,前端直传
1. WED端直传的流程图
SecretId SecretKey等参数可以参考官方文档获取
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.24</version>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>cos-sts-java</artifactId>
<version>3.0.8</version>
</dependency>
2. 请求用户服务器获取到密钥信息
public JSON uploading() throws Exception {
TreeMap<String, Object> config = new TreeMap<String, Object>();
config.put("SecretId", secretId);
config.put("SecretKey", secretKey);
config.put("durationSeconds", durationSeconds);
config.put("bucket", bucket);
config.put("region", region);
config.put("allowPrefix", allowPrefix);
String[] allowActions = new String[]{
"name/cos:PutObject",
"name/cos:PostObject",
"name/cos:InitiateMultipartUpload",
"name/cos:ListMultipartUploads",
"name/cos:ListParts",
"name/cos:UploadPart",
"name/cos:CompleteMultipartUpload"
};
config.put("allowActions", allowActions);
JSONObject credential = CosStsClient.getCredential(config);
JSON parse = JSONUtil.parse(credential.toString());
return parse;
}
{
"code": 200,
"message": "操作成功",
"data": {
"credentials": {
"tmpSecretKey": "******zi7CVEhVM+uodU0/DS2/fQC+yx8ZltU=",
"tmpSecretId": "******6J4osSrP1c3Ufv8DJYudtkc9_UNsGlflrR3aHjvTbEIMp25CJbtT4b_tC1Xn",
"sessionToken": "******29d9a22d392a5985c07746bb4b45opyVxA3Sy6GIQ-Db3982acCSF6MgS8w4eT65hO9x7oXa9qcckMtsam8vz94d-BoVknEysSns-vcfXQMLLQTsvvb8FaEErhN6_JJePJKI8TK4MmiMdY0t7X95muYaQf9R1DtUDdWcJIPnqkmjYEJ_HVkyTn3Zu01bf6OURfU-WP205XUqQUuDGfw5KmVabasyXXLa660n4s0VoQDK8JYvEeCUIJ4vtoK9sJwcr7OYqFaHr2E8RUQq5jOU-6sbAv5_GYQm-5zhlOZiFAOqcifPwSSCfyywDiIco95LYHUIfdruFUPgurXouxn2qFO7oHArOxUkHVASn6Thp1cQZ3Hh2JQYexHlr4-6qhGdsgc90F_T9ve4uW07h0OeFhob1htMAMY7CI9kaohGCA5giy3gC_zFUBa3P1XZ3Qidr5B03TcDi7Tyuf8gjBPLTgjYaD1QYjNIst9Zd9w7KnUemrQj62_x3gcHcbBaRa7xsaEXwWQkAW6eee1qY8WLmYfgFNjipZq-CBi3piHjOWBnGbLDnk5ytFldE2QhvoHI7j8Y2LGQHL-CF7lx9XGy1J11xuCv"
},
"expiredTime": 1606480458,
"requestId": "******-5e84-41f3-88ad-f3cd7f474b0f",
"expiration": "******-11-27T12:34:18Z",
"startTime": 1606478658
}
}
2. 客户端携带签名上传文件
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Put 上传</title>
<style>
h1, h2 {
font-weight: normal;
}
#msg {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Ajax Put 上传</h1>
<input id="fileSelector" type="file">
<input id="submitBtn" type="submit">
<div id="msg"></div>
<script src="https://unpkg.com/cos-js-sdk-v5/demo/common/cos-auth.min.js"></script>
<script>
(function () {
// 请求用到的参数
var Bucket = 'test-1250000000';
var Region = 'ap-guangzhou';
var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
// 对更多字符编码的 url encode 格式
var camSafeUrlEncode = function (str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
};
// 计算签名
var getAuthorization = function (options, callback) {
// var url = 'http://127.0.0.1:3000/sts-auth' +
var url = '../server/sts.php';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
var credentials;
try {
credentials = (new Function('return ' + xhr.responseText))().credentials;
} catch (e) {}
if (credentials) {
callback(null, {
XCosSecurityToken: credentials.sessionToken,
Authorization: CosAuth({
SecretId: credentials.tmpSecretId,
SecretKey: credentials.tmpSecretKey,
Method: options.Method,
Pathname: options.Pathname,
})
});
} else {
console.error(xhr.responseText);
callback('获取签名出错');
}
};
xhr.onerror = function (e) {
callback('获取签名出错');
};
xhr.send();
};
// 上传文件
var uploadFile = function (file, callback) {
var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
getAuthorization({Method: 'PUT', Pathname: '/' + Key}, function (err, info) {
if (err) {
alert(err);
return;
}
var auth = info.Authorization;
var XCosSecurityToken = info.XCosSecurityToken;
var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('Authorization', auth);
XCosSecurityToken && xhr.setRequestHeader('x-cos-security-token', XCosSecurityToken);
xhr.upload.onprogress = function (e) {
console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
};
xhr.onload = function () {
if (/^2\d\d$/.test('' + xhr.status)) {
var ETag = xhr.getResponseHeader('etag');
callback(null, {url: url, ETag: ETag});
} else {
callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
}
};
xhr.onerror = function () {
callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
};
xhr.send(file);
});
};
// 监听表单提交
document.getElementById('submitBtn').onclick = function (e) {
var file = document.getElementById('fileSelector').files[0];
if (!file) {
document.getElementById('msg').innerText = '未选择上传文件';
return;
}
file && uploadFile(file, function (err, data) {
console.log(err || data);
document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
});
};
})();
</script>
</body>
</html>
前端如下图:
二、后端上传
public String uploadServer(MultipartFile file) throws ApiException {
COSClient cosclient = null;
try {
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
InputStream inputStream = file.getInputStream();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
String newFileName = prefix + "/" + year + "/" + UUID.randomUUID() + suffix;
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
Region regionId = new Region(region);
ClientConfig clientConfig = new ClientConfig(regionId);
cosclient = new COSClient(cred, clientConfig);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(inputStream.available());
cosclient.putObject(bucket, newFileName, inputStream, metadata);
return this.path + "/" + newFileName;
} catch (Exception e) {
throw new ApiException(e.getMessage());
} finally {
cosclient.shutdown();
}
}