1、拿到腾讯云SecretId和SecretKey
https://console.cloud.tencent.com/cam/capi
2、通过SecretId和SecretKey请求tmpSecretId、tmpSecretKey和sessionToken字段
此处以node.js代码示例
官方demo:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/sts.js
需要修改下面几个地方,之后运行npm run sts-server,打开浏览器请求http://localhost:3000/sts 即可拿到tmpSecretId、tmpSecretKey等
3、第三步就该生成签名
如果需要前端生成签名,需要后端把获取到的tmpSecretId、tmpSecretKey传给前端
前端将生成签名工具保存本地:签名工具地址
调用签名工具api生成签名,authData即是签名
![在这里插入图片描述](https://img-blog.csdnimg.cn/44dbc40023ef4fc4ba4a9eeb74d1b77e.png
这个时候就该前端去选择文件上传,示例
uploadFile = (filePath: string): void => {
var Key = filePath.substr(filePath.lastIndexOf("/") + 1); // 这里指定上传的文件名
var signPathname = "/" + Bucket + "/"; // PostObject 接口 Key 是放在 Body 传输,所以请求路径和签名路径是 /
const AuthData = CosAuth({
SecretId: "",
SecretKey: "",
Method: "POST",
Pathname: signPathname
});
// const prefix = "https://" + Bucket + ".cos." + Region + ".myqcloud.com/";
const prefix = "https://cos." + Region + ".myqcloud.com/" + Bucket + "/"; // 上传地址固定
console.log(AuthData, Key);
const requestTask = Taro.uploadFile({
url: prefix,
name: "file",
filePath: filePath,
formData: {
key: Key, // 文件名
Signature: AuthData, // 签名
success_action_status: 200,
"x-cos-security-token":"第一步生成的sessionToken",
"Content-Type": ""
},
success: function (res) {
console.log("上传成功", res);
}
});
requestTask.onProgressUpdate(function (res) {
console.log("进度:", res);
});
}
wx.chooseImage({
count: 1, // 默认9
sizeType: ["original"], // 可以指定是原图还是压缩图,这里默认用原图
sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
success: function (res: any) {
uploadFile(res.tempFiles[0].path);
}
});