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);
}
更多推荐
已为社区贡献4条内容
所有评论(0)