1.何时需要从前端直接上传文件到腾讯云
大多数情况下文件上传是将文件传给后端,后端再处理上传至腾讯云的逻辑。
但也有一些情况,比如上传1000个用户同时上传,上传了1000个文件给服务器,由于上传文件耗时相对较长,就会造成堵塞。这时,就需要从前端直接上传文件到腾讯云的这样1000个用户都通过自己的浏览器调用不同的腾讯云上传接口,就可以保证性能啦
#1腾讯云的使用
- 注册腾讯云账号(腾讯云cos官方文档)。
- 创建腾讯云存储桶。
- 得到应用密钥和应用标识。
#2 具体使用
1.安装腾讯云 npm i cos-js-sdk-v5。
2.使用 el-upload 自定义上传
<el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadImage">
3.实现文件上传方法
校验
// 检查函数 判断文件的类型还有大小 return true(继续上传)/false(停止上传)
beforeAvatarUpload(file) {
const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
const isLt5M = file.size / 1024 / 1024 < 5 // 5M
const timeout=new Date(this.deadTime + ' 23:59:59') < new Date()
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
}
if (!isLt5M) {
this.$message.error('上传头像图片大小不能超过 5MB!')
}
if (timeout) { this.$message.error(message: '超过上传时间,禁止上传');
return isJPG && isLt5M && !timeout
}
import COS from 'cos-js-sdk-v5'
// 选择图片上传
uploadImage(params) {
console.log(params.file)
const cos = new COS({
SecretId: 'AKIDQmu0HrSQcZeU3cqA4iCcmgYidIhrQr4jy7',
SecretKey: 'jDRPmTx8rrdBTWXINPltwjKvJRmqfEYl'
}) // 完成 COS 对象的初始化
cos.putObject({
Bucket: ifer, // 存储桶名称
Region: 'ap-nanjing', // 地域名称
Key: params.file.name, // 文件名称
StorageClass: 'STANDARD', // 固定值
Body: params.file // 上传文件对象
onHashProgress: function (progressData) { console.log('校验中', JSON.stringify(progressData)); },
onProgress: function (progressData) { console.log('上传中', JSON.stringify(progressData))
}, (err, data) => {
if (data.statusCode === 200 && data.Location) {
// 拿到了腾讯云返回的地址
// 通过 input 自定义事件将地址传出去
this.$emit('input', 'http://' + data.Location) // 将地址返回了
} else {
this.$message.error(err.Message) // 上传失败提示消息
}
})
}
此处是纯前端上传,配合后端 参考链接:juejin.cn/post/702031…