Vue 使用 Element-ui upload 组件实现上传文件到七牛和数据回显

2,164 阅读1分钟

文件上传

在这里插入图片描述

<el-upload
       	ref="fileUpload"
        action="https://up-z1.qiniup.com"
        :auto-upload="false"
        :data="{
            token: qnToken,
            key: fileKey
        }"
        :on-change="changeUploadFile"
        :on-success="upFileScuccess"
        :on-remove="removeFile"
        :file-list="form.fileList"
        :limit="5"
    >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
</el-upload>

action:地址根据情况自行更换;
qnToken:七牛需要的token,从后台获取;
fileKey:见下文;
limit:限制文件的个数。

methods: {
		//文件状态改变
        changeUploadFile(file) {
            const suffix = file.name.split('.')
            const ext = suffix.splice(suffix.length - 1, 1)[0]
            //在文件名后面加一个时间戳,确保相同文件的key唯一
            this.fileKey = `file/${suffix.join(
                '.'
            )}_${new Date().getTime()}.${ext}`
            setTimeout(() => { 
                this.$refs['fileUpload'].submit()
            }, 500)
        },
        //文件上传成功
        upFileScuccess(response, file) {
        	//多个文件放到数组里,存的字段名为name,url,数据回显时有用!
            this.form.fileList.push({ name: file.name, url: `你的CDN地址/${response.key}` })
        },
        //文件列表移除文件
        removeFile(file, fileList) {
            let url = `你的CDN地址/${file.response.key}`
            console.log(url);
            //文件名不是唯一的,key是唯一的,所以要根据url来去重
            for (let i = 0; i < this.form.fileList.length; i++) {
                if (this.form.fileList[i].url == url) {
                    this.form.fileList.splice(i, 1)
                }
            }
        },
}

数据回显

把数据给后台的时候,如果fileList为上面的格式,那么你怎么给他的就让他怎么给你就好了,如下。 在这里插入图片描述 请求数据回来之后,直接给data中的fileList赋值,回显完成。