第一步、引入upload组件
<el-upload
:class="{disable:fileList.length > 0}" //当组件挂载了一个文件之后,加号就会消失
action="#" //为必填属性:文件上传的地址
list-type="picture-card" // 组件的样式类型
:file-list="fileList" //必填属性:挂载到组件的文件的列表,fileList为一个数组,每一个元素都是一个文件对象
:on-change="onChange" // 每当有文件上传时就会调用这个函数,自带两个参数,第一个为新的文件列表数组,第二个为新上传的文件对象
:on-remove="onRemove" // 每当有文件从组件被删除就会调用这个函数,自带两个参数,第一个为新的文件列表数组,第二个为删除的文件对象
:before-upload="beforeUpload" // 上传文件前会触发,一般用于文件的校验,自带一个参数,为新上传的文件对象
:http-request="httpRequest" // 文件上传到仓库后会调用,自带一个参数,为文件上传行为的对线
>
<i class="el-icon-plus" />
</el-upload>
// style
.disable{
::v-deep .el-upload--picture-card{
display: none
}
}
第二步,配置cos并实例化cos对象
下载引入cos npm i cos-js-sdk-v5
import COS from 'cos-js-sdk-v5'
var cos = new COS({
SecretId: '',
SecretKey: ''
})
第三步,声明上传文件各阶段的函数
methods: {
onChange(data, newList) {
this.fileList = newList
},
onRemove(data, newList) {
this.fileList = newList
},
beforeUpload(file) {
console.log(file)
const whiteList = ['image/jpeg', 'image/png']
if (whiteList.indexOf(file.type) === -1) {
this.$message.error('只支持jpeg/png格式')
return false
}
if (file.size > 1 * 1024 * 1024) {
this.$message.error('文件不能超过1m')
return false
}
},
httpRequest(params) {
console.log('上传成功', params)
cos.putObject({
Bucket: '腾讯云储存桶名字',
Region: 'ap-guangzhou',
Key: 文件的姓名,
StorageClass: 'STANDARD',
Body: params.file,
onProgress: function(progressData) {
console.log(JSON.stringify(progressData))
}
}, (err, data) => {
console.log(err || data)
if (!err) {
this.fileList[0].status = 'success'
this.fileList[0].url = 'http://' + data.Location
this.fileList[this.fileList.length - 1]['url'] = 'http://' + data.Location
this.fileList[this.fileList.length - 1]['status'] = 'success'
console.log(this.fileList)
}
})
}
}