本文主要是介绍上传文件到腾讯云COS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import COS from 'cos-js-sdk-v5' // 通过npm安装
import md5 from 'blueimp-md5' // 通过npm安装
class Auth { // 认证信息constructor (bucket, region, TmpSecretId, TmpSecretKey, XCosSecurityToken, ExpiredTime) {this.bucket = bucketthis.region = regionthis.TmpSecretId = TmpSecretIdthis.TmpSecretKey = TmpSecretKeythis.XCosSecurityToken = XCosSecurityTokenthis.ExpiredTime = ExpiredTime}
}function formatFileName (fileName, dirName) { // 文件命名规则:业务名+ '/' + md5(文件名+时间戳).文件扩展名let dotIndex = fileName.lastIndexOf('.')let baseName = fileName.substring(0, dotIndex) // 获取文件基础名let extensionName = fileName.substring(dotIndex + 1) // 获取文件扩展名let timestamp = new Date().getTime() // 获取当前时间戳,以毫秒为单位let result = dirName + '/' + md5(baseName + timestamp) + '.' + extensionNamereturn result
}export default class QCloudCos {constructor (getAuthPromise) { //传入用于获取认证信息的promise,由本模块在需要的时候自动获取this.getAuthPromise = getAuthPromisethis.getAuth().then(() => {this.cos = new COS({getAuthorization: (options, callback) => {let obj = {TmpSecretId: this.auth.TmpSecretId,TmpSecretKey: this.auth.TmpSecretKey,XCosSecurityToken: this.auth.XCosSecurityToken,ExpiredTime: this.auth.ExpiredTime}callback(obj)}})})}getAuth () {return this.getAuthPromise().then((res) => {this.auth = new Auth(res.bucket, res.region, res.TmpSecretId, res.TmpSecretKey, res.XCosSecurityToken, res.ExpiredTime)let interval = setInterval(() => { // 倒计时,token失效则重新获取this.auth.ExpiredTime -= 1if (this.auth.ExpiredTime <= 0) {clearInterval(interval)this.getAuth()}}, 1000)})}uploadFiles (files, dirName, callback) {let array = []for (let i = 0; i < files.length; i++) {array.push({Bucket: this.auth.bucket,Region: this.auth.region,Key: formatFileName(files[i].name, dirName),Body: files[i]})}this.cos.uploadFiles({files: array,SliceSize: 1024 * 1024, // 小于等于该数值会使用 putObject 上传,大于该数值会使用 sliceUploadFile 上传onProgress: function (info) {let percent = parseInt(info.percent * 10000) / 100let speed = parseInt(info.speed / 1024 / 1024 * 100) / 100console.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;')},onFileFinish: function (err, data, options) {console.log(options.Key + '上传' + (err ? '失败' : '完成'))}}, function (err, data) {callback(err || data)})}
}
使用步骤示例:
1.初始化:
this.qCloudCos = new QCloudCos(getCosToken) // 传入一个返回Auth对象的promise
2.上传图片:
this.qCloudCos.uploadFiles(this.pics, 'feedback', (data) => { // 传入3个参数:file数组,业务名(作为文件目录名),上传结果回调。if (!data.files) {return}let result = []for (let i = 0; i < data.files.length; i++) {let item = data.files[i]if (!item.data) { // 图片上传失败return}result.push('https://' + item.data.Location) // 上传到CDN之后的文件URL}
})
这篇关于上传文件到腾讯云COS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!