import COS from 'cos-js-sdk-v5'; import * as qCloudCosApi from '../api/qcloud-cos'; export function upload(file) { console.log("file", file); return new Promise((resolve, reject) => { qCloudCosApi.getTmpCosCredential({ ext: 'jpg' }).then((data) => { console.log("data", data) // { // "tmpSecretId": "", // "tmpSecretKey": "", // "sessionToken": "", // "objectKey": "", // "startTimestamp": 1680534188320, // "expiredTimestamp": 1680535988320, // "bucket": "epp-1302260381", // "region": "ap-shanghai" // } let cos = new COS({ // getAuthorization 必选参数 getAuthorization: function (options, callback) { // 异步获取临时密钥 callback({ TmpSecretId: data.tmpSecretId, TmpSecretKey: data.tmpSecretKey, SecurityToken: data.sessionToken, // 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误 StartTime: Math.floor(data.startTimestamp / 1000), // 时间戳,单位秒,如:1580000000 ExpiredTime: Math.floor(data.expiredTimestamp / 1000), // 时间戳,单位秒,如:1580000000 }); } }); console.log("cos", cos) cos.putObject({ Bucket: data.bucket, /* 填入您自己的存储桶,必须字段 */ Region: data.region, /* 存储桶所在地域,例如ap-beijing,必须字段 */ Key: data.objectKey, /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */ Body: file, }, function (err, data) { if (err) { reject(err); } else { resolve(data); } }); }).catch((err) => { reject(err) }) }) };