uni-app H5 上传到腾讯云
腾讯云申请对象存储,用户组申请子账号,创建存储桶;
前端代码
下面展示一些 内联代码片
。
// An highlighted block
<view class="addImg" @tap="addImg">
<view class="textJ">+</view>
<view class="textM">添加图片</view>
</view>
addImg: function() {
var that = this
console.log(that.realnameList.length)
if (this.realnameList.length >= 9) {
uni.showToast({
title: "上传图片请勿多于9张!",
icon: "none",
duration: 1000
})
return
}
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function(res) {
if(res.tempFiles[0].size > 2 * 1024 * 1024){
uni.showToast({
title: "图片请勿超过2MB",
icon: "none",
duration: 1000
})
return
}
console.log(res.tempFiles[0])
that.realnameList.push({
'path': res.tempFiles[0].path, 'body': res.tempFiles[0], 'format': res.tempFiles[0].name.substring(res.tempFiles[0].name.lastIndexOf('.'))
})
},
fail: function(error) {
console.log(error)
uni.showToast({
title: "请重新选择",
icon: "none",
duration: 1000
})
}
})
},
getRealImgT: async function() {
var that = this
// var ossList = await this.getSignature();
var realnameT = '';
if (that.realnameList.length > 0) {
for (let item of this.realnameList) {
item.path = await that.upLoadFileCos(item.body, item.format, "realname")
realnameT += item.path + ',';
}
}
that.realnameT = realnameT
return realnameT
},
upLoadFileCos: async function(filebody, format, texttips) {
var that = this
var dir = "文件存储地址"
// console.log(tempPath.substring(tempPath.length - 10).toUpperCase())
// var newdate = new Date().getTime()
var newName = uni.getStorageSync('mbId') + '_' + texttips + format
var cos = await that.getObject()
console.log(cos)
return new Promise(function(resolve, reject) {
cos.putObject({
Bucket: '存储桶名称',
Region: '地域名称',
Key: dir + newName,
// FilePath: tempPath,
StorageClass: 'STANDARD',
Body: filebody,
onProgress: function(info) {
// console.log(JSON.stringify(info));
resolve("文件地址")
}
}, function(err, data) {
console.log(err || data);
// console.log(err);
// console.log(data);
});
})
},
getObject() {
var that = this
return new COS({
// ForcePathStyle: true, // 如果使用了很多存储桶,可以通过打开后缀式,减少配置白名单域名数量,请求时会用地域域名
getAuthorization: function(options, callback) {
// 异步获取临时密钥
uni.request({
url: that.urlPath + 'login/getPolicyCos',
data: {
bucket: "存储桶名称", //固定写法
region: "地域名称", //固定写法
},
// beforeSend: function (xhr) {
// xhr.setRequestHeader('Content-Type', 'application/json');
// },
dataType: 'json',
success: function(result) {
// console.log(result.data);
var data = result.data;
var credentials = data.credentials;
// console.log(data.credentials);
if (!data || !credentials) return console.error(
'credentials invalid');
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
XCosSecurityToken: credentials.sessionToken,
// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
StartTime: data.startTime, // 时间戳,单位秒,如:1580000000
ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000900
});
}
});
}
});
},
```
CORS blocked or network error at XMLHttpRequest.c.onerror
解决方法:存储桶>安全管理-cors跨域请求设置
自我纪录,欢迎讨论!