vue上传文件并显示进度条

html

<el-upload 
    :action="uploadFileReq" 
    ref="upload" 
    :on-change="handleChange" 
    :on-success="handleSuccess" 
    :on-progress="handleProgress" 
    :auto-upload="false" 
    :file-list="fileList" 
    :show-file-list="false" drag>

    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>

</el-upload>

<el-button type="primary" @click="sendClick">发送</el-button>

 方法一

手动使用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

<!-- 选择文件 -->
<el-upload 
    :action="uploadFileReq" 
    ref="upload" 
    :on-change="handleChange" 
    :on-success="handleSuccess" 
    :on-progress="handleProgress" 
    :auto-upload="false" 
    :file-list="fileList" 
    :show-file-list="false" drag>
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>

<el-button type="primary" @click="sendClick">上传</el-button>

<el-button type="primary" @click="downloadFile(292,'test.txt')">下载</el-button>

<!-- 进度条 -->
<div v-if="elProgress" class="up_progress">
    <div class="text_con">{{progressText}}</div>
    <el-progress :percentage="progressPercent" :text-inside="true" :stroke-width="16" status="success"> </el-progress>
    <div class="cancel_btn">
        <el-button type="success" round @click="cancelUpload" v-if="!switchBtn">取消上传</el-button>
        <el-button type="success" round @click="cancelDownload" v-else>取消下载</el-button>
    </div>
</div>

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
<button onclick="download(292)">测试下载</button>

// js
<script>
    function load() {
        console.log('开始下载')
    }
    function closeLoad() {
        console.log('下载完成')
    }
    function download(id) {
        load()
        let url = `http://127.0.0.1/download?id=${id}`
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
            console.log(xhr)
            if (this.status === 200) {
                var blob = this.response
                if (navigator.msSaveBlob == null) {
                    let a = document.createElement('a')
                    let headerName = xhr.getResponseHeader('Content-disposition')
                    let fileName = decodeURIComponent(headerName).substring(20)
                    a.download = fileName
                    a.href = URL.createObjectURL(blob)
                    document.body.appendChild(a)
                    a.click()
                    URL.revokeObjectURL(a.href)
                    document.body.removeChild(a)
                } else {
                    navigator.msSaveBlob(blob, fileName)
                }
            }
            closeLoad()
        }
        xhr.send()
    }
</script>

获取文件方法

        // 选择文件
		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); 
		}

  • 11
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中实现文件上传进度条可以通过使用axios库来发送文件请求,并结合HTML5的FormData对象来实现。以下是一个简单的示例代码: 首先,在你的Vue组件中,引入axios库: ```javascript import axios from 'axios'; ``` 然后,创建一个data属性来存储上传进度相关的数据: ```javascript data() { return { file: null, // 保存要上传的文件 progress: 0, // 上传进度 }; }, ``` 接下来,创建一个方法来处理文件上传: ```javascript methods: { handleFileUpload(event) { this.file = event.target.files[0]; // 获取要上传的文件 // 创建FormData对象 let formData = new FormData(); formData.append('file', this.file); // 发送文件请求 axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', }, onUploadProgress: progressEvent => { this.progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); // 更新上传进度 }, }) .then(response => { // 处理上传成功的响应 }) .catch(error => { // 处理上传失败的错误 }); }, }, ``` 最后,在模板中添加文件上传的input元素和进度条: ```html <template> <div> <input type="file" @change="handleFileUpload" /> <div>{{ progress }}%</div> <div class="progress-bar"> <div class="progress-bar-inner" :style="{ width: progress + '%' }"></div> </div> </div> </template> <style> .progress-bar { width: 200px; height: 20px; border: 1px solid #ccc; } .progress-bar-inner { height: 100%; background-color: #00a0e9; } </style> ``` 这样,当用户选择文件后,文件将被上传到服务器,并且进度条会实时更新上传进度。注意要将`/upload`替换为你的服务器端接收文件上传的URL。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值