vue上传文件并显示进度条

html



    
    
将文件拖到此处,或点击上传
发送

 方法一

手动使用submit()上传

        // 文件操作
        handleChange(file, fileList) {
            console.log(file)
            console.log(fileList)
        },
        // 点击上传
        sendClick() {
            this.$refs.upload.submit()
        },
        // 文件上传时
        handleProgress(event) {
            console.log(event)
        },
        // 上传成功
        handleSuccess(res) {
            console.log(res)
        },

方法二

使用axios上传

// 文件操作
handleChange(file, fileList) {
    console.log(file)
    console.log(fileList)
    let formData = new FormData()
    formData.append('file', file.raw)
    this.files = formData
},
// 点击上传
async sendClick() {
    const { data: res } = await axios({
        method: 'post',
        url: this.uploadFileReq,
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        data: this.files,
    })
    console.log(res)
},

上传/下载进度条

html



    
    
将文件拖到此处,或点击上传
上传 下载
{{progressText}}
取消上传 取消下载

js

keepFileList 用来备份选择的文件列表,因取消下载后文件列表会被清空,导致不能继续上传

new Vue({
    el: '#app',
    data: {
        progressText: '',
        progressPercent: 0,
        elProgress: false,
        switchBtn: true,
        fileList: [],
        keepFileList: [],    
    },
    methods: {
        // 文件操作
        handleChange(file, fileList) {
            console.log(fileList)
            this.keepFileList = fileList
        },
        // 上传
        sendClick() {
            console.log('开始上传')
            this.progressPercent = 0
            this.switchBtn = false
            this.$refs.upload.submit()
            this.progressText = '正在上传'
        },
        // 文件上传时
        handleProgress(event) {
            console.log(event)
            this.elProgress = true
            if (this.progressPercent < 99) {
                this.progressPercent = parseInt(event.percent)
            } else {
                this.progressText = '正在解析'
            }
        },
        // 上传成功
        handleSuccess(res) {
            console.log(res)
            if (res.success == 1) {
                this.progressPercent = 100
                this.progressText = '上传成功'
            } else {
                console.log('上传失败')
            }
            this.elProgress = false
        },
        // 取消上传
        cancelUpload() {
            this.$refs.upload.abort()
            this.$refs.upload.clearFiles()
            this.fileList = this.keepFileList.concat()
            this.fileList[0].status = 'ready'
            this.elProgress = false
            console.log('取消上传')
        },
        // 下载
        async downloadFile(id, fileName) {
            console.log('开始下载')
            this.progressPercent = 0
            this.switchBtn = true
            let _this = this
            const res = await axios({
                url: `${this.downloadFileReq}?id=${id}&downAre=0`,
                responseType: 'blob',
                onDownloadProgress: function (progressEvent) {
                    console.log(progressEvent)
                    if (progressEvent.lengthComputable) {
                        _this.elProgress = true
                        _this.progressText = '正在解析'
                        _this.progressPercent = parseInt((progressEvent.loaded / progressEvent.total) * 100)
                    }
                },
            })
            console.log(res)
            let blob = new Blob([res.data])
            let downloadElement = document.createElement('a')
            let href = window.URL.createObjectURL(blob) //创建下载的链接
            // 响应头里获取文件名,需要后端放行
            let filename1 = decodeURI(res.headers['content-disposition'].replace('attachment;filename=', ''))
            // let filename1 = res.headers['content-disposition'].replace('attachment;filename=', '')
            console.log(filename1)
            downloadElement.style.display = 'none'
            downloadElement.href = href
            downloadElement.download = filename1 //下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement) //下载完成移除元素
            window.URL.revokeObjectURL(href) //释放掉blob对象
            this.elProgress = false
            console.log('下载完成')
        },
        // 取消下载
        cancelDownload() {
            location.reload()
        },
    } 
})

 后端放行响应头代码

// 放行Content-disposition响应头
response.setHeader("Access-Control-Expose-Headers", "Content-disposition");

axios上传进度方式

// 文件操作
handleChange(file, fileList) {
    console.log(file)
    console.log(fileList)
    let formData = new FormData()
    formData.append('file', file.raw)
    this.files = formData
},
// 点击上传
async sendClick() {
    const { data: res } = await axios({
        method: 'post',
        url: this.uploadFileReq,
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        data: this.files,
        onUploadProgress: function (progressEvent) {
                    console.log(progressEvent)
                    if (progressEvent.lengthComputable) {
                        _this.elProgress = true
                        _this.progressText = '正在上传'
                        _this.progressPercent = parseInt((progressEvent.loaded / progressEvent.total) * 100)
                    }
                },
    })
    console.log(res)
},

模拟上传进度(定时器)

data:{
    times: null,
    progressPercent: 0,
    elProgress: false,
},

method:{
    // 文件上传时
    handleProgress(event) {
        console.log(event)
        this.elProgress = true
        //使用定时器来制作进度条
        this.times = setInterval(() => {
            this.progressPercent++
            if (this.progressPercent > 90) {
                clearInterval(this.timer)
                this.times = null
            }
        }, 900)
    },
    // 上传成功
    handleSuccess(res) {
        console.log(res)
        if (res.success == 1) {
            this.progressPercent = 100
            this.progressText = '上传成功'
        } else {
            console.log('上传失败')
        }
        this.elProgress = false
    },
}

附赠

ajax上传

// html


// js

获取文件方法

        // 选择文件
		handleChange(file, fileLists) {
			console.log(file);
			console.log(fileLists);
            // 获取文件对象
            console.log(file.raw)
			// 本地服务器路径
			console.log(URL.createObjectURL(file.raw));
			// 本地电脑路径
			console.log(document.getElementsByClassName("el-upload__input")[0].value); 
		}

你可能感兴趣的:(vue,javascript,vue.js,elementui,javascript)