对象存储 文件上传
# npm i qcloud-cos-sts --save
var STS = require('qcloud-cos-sts');
// 配置参数
var config = {
secretId: 'AKIDb2D8mAI9j36sNbYEdlcCWZLq65nLbaIk', //修改
secretKey: 'C7l9G6ewxhBOL1QYQ1KM8droUu3vWtzo', //修改
proxy: '',
durationSeconds: 1800,
// 放行判断相关参数
bucket: 'yanxianfei-1307931282', //修改
region: 'ap-beijing', //修改
allowPrefix: '*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
// 简单上传和分片,需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
allowActions: [
// 简单上传
'name/cos:PutObject',
'name/cos:PostObject',
// 分片上传
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload'
],
};
// 腾讯云生成临时秘钥
// 创建临时密钥服务
var app = express();
app.use(bodyParser.json());
// 支持跨域访问
app.all('*', function (req, res, next) {
res.header('Content-Type', 'application/json');
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:88');
res.header('Access-Control-Allow-Headers', 'origin,accept,content-type');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
if (req.method.toUpperCase() === 'OPTIONS') {
res.end();
} else {
next();
}
});
// 临时密钥接口
app.all('/sts', function (req, res, next) {
// TODO 这里根据自己业务需要做好放行判断
// 获取临时密钥
var shortBucketName = config.bucket.substr(0 , config.bucket.lastIndexOf('-'));
var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
var policy = {
'version': '2.0',
'statement': [{
'action': config.allowActions,
'effect': 'allow',
'principal': {'qcs': ['*']},
'resource': [
'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
],
}],
};
STS.getCredential({
secretId: config.secretId,
secretKey: config.secretKey,
proxy: config.proxy,
durationSeconds: config.durationSeconds,
policy: policy,
}, function (err, tempKeys) {
var result = JSON.stringify(err || tempKeys) || '';
res.send(result);
});
});
# 请求/sts接口 返回秘钥
![image.png](https://upload-images.jianshu.io/upload_images/24202745-6c5b1dc035eca137.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
html 上传示例
<!DOCTYPE html>
<html>
<head>
<TITLE> ZTREE DEMO - beforeCheck / onCheck</TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="./sdk/cos-js-sdk-v5.min.js" charset="utf-8"></script>
<script src="./md5.js"></script>
</head>
<body>
<button type="button" class="layui-btn" id="up_pic_btn">多图片上传</button>
<input id="upload-file" type="file" title="上传图片" multiple style="display: none;" accept="image/*">
<script type="text/javascript">
var cos = new COS({
getAuthorization: function (options, callback) {
// 异步获取临时密钥
$.ajax({
method: 'get',
url: 'http://localhost:4000/sts',
data: '',
dataType: 'json',
success: function (res) {
console.log(res,'8888888888888');
var credentials =res.credentials;
if (!res || !credentials) return console.error('credentials invalid');
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
SecurityToken: credentials.sessionToken,
// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
StartTime: res.startTime, // 时间戳,单位秒,如:1580000000
ExpiredTime: res.expiredTime, // 时间戳,单位秒,如:1580000900
ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用
});
}
});
}
});
$('#up_pic_btn').on('click',function(){
$('#upload-file').click();
});
$('#upload-file').on('change',function(e){
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var h = date.getHours();
var m = date.getMinutes()
if (month < 10) { month = "0" + month;}
if (day < 10) { day = "0" + day; }
if (h < 10) { h = "0" + h;}
if (m < 10) {m = "0" + m;}
time = year + month + day;
var s = date.getTime()
var filesArr = this.files;
let keytong = [];
var yasuo = ''
$.each(this.files, function (idx, it) {
let size = it.size;
var _headers = {}
let img_name = it.name.split('.')[0]
let img_type = it.name.split('.')[1]
console.log(img_name+img_type);
if(parseFloat(size/1024/1024)> 1){
yasuo = 1;
_headers = {'Pic-Operations':'{"is_pic_info": 1, "rules": [{"fileid":"thumb_'+ s +hex_md5(img_name)+'.'+img_type +'", "rule": "imageMogr2/format/webp"}]}'}
}
let set_img_url = time + '/' + s+hex_md5(img_name)+'.'+img_type;
console.log(set_img_url,'/set_img_urlset_img_url');
keytong.push({
Bucket: 'yanxianfei-1307931282', // Bucket 格式
Region: 'ap-beijing', /* 存储桶所在地域,必须字段 */
Key: "upimages/"+set_img_url,
Body: it,
Headers:_headers,
onTaskReady: function(taskId) {
// console.log(taskId);
}
})
yasuo = '';
});
console.log(keytong,'keytongkeytongkeytongkeytong');
cos.uploadFiles({
files: keytong,
SliceSize: 1024 * 1024 * 10, /* 设置大于10MB采用分块上传 */
onProgress: function (info) {
var percent = parseInt(info.percent * 10000) / 100;
var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
console.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
},
onFileFinish: function (err, data, options) {
console.log(data, + '上传' + (err ? '失败' : '完成'));
if(err){
// layer.msg('上传失败')
// layer.close(loading);
return false
}
let src = '';
src = data.Location; //原图
if(data.UploadResult){
src = data.UploadResult.ProcessResults.Object.Location; //压缩图
}
},
}, function (err, result) {
console.log(result,'////99999999999999999999999999999999999999');
});
})
</script>
</body>
</html>