腾讯云COS前端直传
首先你需要创建应该储存桶,得到 Bucket(存储桶名称) 和 Region(地域名称)
进入基础配置页面,设置跨域访问的基本设置,详情看文档
获取临时密钥,服务端使用固定密钥
SecretId
、SecretKey
向 STS 服务获取临时密钥,得到tmpSecretId
、tmpSecretKey
、sessionToken
。各语言Demo前端通过
tmpSecretId
、tmpSecretKey
,计算签名。下列使用vue
调用JavaScript SDK
为示例:<template> <div class="hello"> <p class="fileT"> 选择文件 <input accept="" type="file" ref="file" id="upload" /> </p> <button class="sure" @click="uploadFile()">上传</button> </div> </template> <script> import COS from "cos-js-sdk-v5"; import axios from "axios"; export default { components: {}, data() { return {}; }, name: "HelloWorld", methods: { getTime() { var date = new Date(); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month + seperator1 + strDate; return currentdate; }, //上传腾讯云 uploadFile() { let result = Object; var cos = new COS({ // 必选参数 getAuthorization: function (options, callback) { axios.post("http://localhost:5010/api/COS/getToken").then((data) => { result = data.data; console.log(result); // this.$options.methods.uploadFile.bind(this)(data.data); callback({ TmpSecretId: result.Credentials.TmpSecretId, TmpSecretKey: result.Credentials.TmpSecretKey, XCosSecurityToken: result.Credentials.Token, StartTime: result.StartTime, // 时间戳,单位秒,如:1580000000 ExpiredTime: result.ExpiredTime, // 时间戳,单位秒,如:1580000900 }); }); }, }); var fileObj = document.getElementById("upload").files[0]; cos.putObject( { Bucket: "myblog-1302916147" /* 必须 */, Region: "ap-guangzhou" /* 存储桶所在地域,必须字段 */, Key: this.$options.methods.getTime() + "/123.jpg" /* 必须 */, StorageClass: "STANDARD", Body: fileObj, // 上传文件对象 onProgress: function (progressData) { console.log(JSON.stringify(progressData)); }, }, function (err, data) { console.log(err || data); } ); }, }, }; </script> <style scoped> </style>