最近项目的一个需求,资源上传到本地服务器太消耗资源了,所以有了需要上传到腾讯云的需求。此贴作为记录和帮助掘友们 技术栈为vue+antdesginVue
先写template模板部分,代码如下:
<div>
<a-upload
name="file"
:multiple="false"
:beforeUpload="beforeUpload"
:customRequest="customRequest"
:accept=".png,.jpg,.jpeg"
:remove="remove"
:showUploadList="false"
>
<a-button> <a-icon type="upload" /> 上传APK </a-button></a-upload
>
</div>
</template>
用的是antdesginVue中的上传组件a-upload,属性:multiple="false"表示只能选择单个文件进行上传。true时为多个文件上传;:beforeUpload="beforeUpload"指定在上传文件之前的验证操作;:customRequest="customRequest"指定自定义的上传方法;:accept=".png,.jpg,.jpeg"设置只允许上传.png,.jpg,.jpeg格式的文件,可以自行修改或者添加,以文件的后缀名为准;- :remove="remove"定义了删除文件的回调方法;:showUploadList="false"设置不显示上传文件列表。
a-upload的属性介绍完毕了,下面开始最重要的js环节(a-upload的其他属性可以在antdesginVue官网搜索查看)。 先引入库,COS是(腾讯云对象存储)库,用于实现文件上传到腾讯云。
import COS from 'cos-js-sdk-v5'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction } from '../api/manage'
定义数据
return {
headers: {},
// url: {
// getKey: '/hhk/file/getKey',
// upLoadFile: '/hhk/file/upFile',
// },
credentials: {
sessionToken: '', //腾讯云需要的验证参数
tmpSecretId: '',
tmpSecretKey: '',
},
}
},
在methods中写好上传前校验的方法,规定上传的大小和上传文件的格式
console.log(file)
const files = ['image/png', 'image/jpg', 'image/jpeg']
if (file.type == 'image/png' || file.type == 'image/jpg') {
if (file.size > 5 * 1024 * 1024) {
this.$message.error('图片上传不超过5M')
}
}
if (!files.includes(file.type)) {
this.$message.error('上传文件类型只能是.png、.jpg')
}
},
最后就是重中之重的上传腾讯云方法了,以下是上传的customRequest方法
console.log(info, '-----')
const { file } = info
this.cos.putObject(
{
Bucket: '' /* 填入您自己的存储桶,必须字段 */,
Region: '' /* 存储桶所在地域,例如ap-beijing,必须字段 */,
Key: '/' + file.name /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */,
Body: file,
headers: {
'Content-type': 'application/json;charset=UTF-8',
},
onProgress: (progressData) => {
console.log(JSON.stringify(progressData))
},
/* 必须,上传文件对象,可以是input[type="file"]标签选择本地文件后得到的file对象 */
},
(err, data) => {
console.log(err, data)
if (!err) {
const url = 'https://' + data.Location
console.log(url)
} else {
console.log(err)
this.$message.error('上传文件错误')
}
}
)
},
这段代码主要就是用cos的putObject方法把文件上传到腾讯云中,具体参数可以在腾讯云的文档中查看,到此就已经上传完成了。如果需要写删除的回调方法的话就在 remove() {}中写。希望可以帮到掘友们!拜了个拜