按照官方给出的列子修改可以直接拿着js用
目录

cosUpload.js(需要补充自己的桶名和地域名)
import request from '../service/request.js'
var CosAuth = require('./cos-auth.min'); // 这里引用了 cos-auth.js,下载地址为 https://unpkg.com/cos-js-sdk-v5/demo/common/cos-auth.min.js
export const uploadFile = function (path) {
return new Promise((resolve, reject) => {
var Bucket = ''; // 桶name
var Region = ''; // 地域name
var ForcePathStyle = false;// 是否使用后缀式,涉及签名计算和域名白名单配置,后缀式说明看上文
// 请求用到的参数
var prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
if (ForcePathStyle) {
// 后缀式请求在签名时域名使用地域域名,而不是存储桶域名,具体说明见本文上述“3.后缀式请求”
prefix = 'https://cos.' + Region + '.myqcloud.com/' + Bucket + '/';
}
// 对更多字符编码的 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 stsCache;
var getCredentials = function (callback) {
if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
callback(data.credentials);
return;
}
request({
method: 'GET',
url: '/neighbourhoodCircle/getTxSignature', // 服务端签名,参考上文说的获取临时密钥
dataType: 'json',
}).then(res => {
if (res.data) {
stsCache = res.data
} else {
wx.showModal({
title: '临时密钥获取失败!',
icon: 'none'
});
}
callback(stsCache);
});
};
// 计算签名
var getAuthorization = function (options, callback) {
getCredentials(function (credentials) {
callback({
XCosSecurityToken: credentials.sessionToken,
Authorization: CosAuth({ // 生成签名
SecretId: credentials.tmpSecretId,
SecretKey: credentials.tmpSecretKey,
Method: options.Method,
Pathname: options.Pathname,
})
});
});
};
// post上传文件
var postFile = function (filePath) {
var Key = filePath.substr(filePath.lastIndexOf('/') + 1); // 这里指定上传的文件名
var signPathname = '/'; // PostObject 接口 Key 是放在 Body 传输,所以请求路径和签名路径是 /
if (ForcePathStyle) {
// 后缀式请求在签名时用的路径,要包含存储桶名称,具体说明见本文上述“3.后缀式请求”
signPathname = '/' + Bucket + '/';
}
getAuthorization({
Method: 'POST',
Pathname: signPathname
}, function (AuthData) {
var requestTask = wx.uploadFile({
url: prefix,
name: 'file',
filePath: filePath,
formData: {
'key': Key,
'success_action_status': 200,
'Signature': AuthData.Authorization,
'x-cos-security-token': AuthData.XCosSecurityToken,
'Content-Type': '',
},
success: function (res) {
var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
if (/^2\d\d$/.test('' + res.statusCode)) { // 上传成功
resolve(url)
} else {
console.log('失败!',res)
}
},
fail: function (res) {
console.log('失败!',res)
}
});
// requestTask.onProgressUpdate(function (res) {
// console.log('进度:', res);
// }); // 上传进度
});
};
postFile(path) // post请求上传
})
};
引用文件
import {
uploadFile
} from '../../../utils/cosUpload'
// 调用方式 (使用wx.chooseMedia得到path)
uploadFile(path).then(res => {
console.log(url) // 上传后的url
})