1、下载小程序cos-wx-sdk-v5
找到cos-wx-sdk-v5.js放到同级目录就可以
2、在common目录下新建 base.js 文件
const COS = require("./cos-wx-sdk-v5.js")
import {
getCoskey
} from '@/utils/server'
const Bucket = ""; /* 填入您自己的存储桶,必须字段 */
const Region = ''; /* 存储桶所在地域,例如ap-beijing,必须字段 */
let cos = new COS({
getAuthorization: function(options, callback) {
uni.request({
url: ", // 获取临时秘钥的接口
data: options.Scope,
success: function(result) {
var data = result.data.data;
var credentials = data && data.credentials;
if (!data || !credentials) return console.error('credentials invalid');
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
// v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
SecurityToken: credentials.sessionToken,
// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
StartTime: data.startTime, // 时间戳,单位秒,如:1580000000
ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000900
ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用
});
}
});
}
})
export function uplodeFile (e) {
cos.uploadFile({
Bucket: ",
Region: "",
Prefix: 'image/*',
Key: 'image/' + e.tempFiles[0].name,
FilePath: e.tempFilePaths[0],
Body: e.tempFiles[0].file,
}, function(err, data) {
wx.hideLoading();
if (data && data.Location) {
wx.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
});
} else {
console.log(err)
wx.showToast({
title: '上传失败',
icon: 'error',
duration: 2000
});
}
})
};