用vuejs写一个断点续传的功能
时间: 2023-05-23 21:04:09 浏览: 88
可以的,具体实现需要使用 axios 库配合后台接口实现文件上传与下载功能,在前端使用 Vue.js 实现进度条与断点续传的逻辑。以下是大致的代码示例:
template:
```html
<template>
<div>
<h3>文件上传</h3>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传</button>
<h3>文件下载</h3>
<input type="text" v-model="fileName" placeholder="请填写文件名" />
<button @click="downloadFile">下载</button>
<div v-if="showProgress" style="margin-top: 20px;">
<p>上传/下载进度:{{ progress }}%</p>
<progress :value="progress" max="100"></progress>
</div>
</div>
</template>
```
script:
```javascript
<script>
import axios from 'axios'
export default {
data () {
return {
file: null,
showProgress: false,
progress: 0,
fileName: ''
}
},
methods: {
handleFileChange (event) {
this.file = event.target.files[0]
},
uploadFile () {
const formData = new FormData()
formData.append('file', this.file)
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (progressEvent) => {
this.progress = parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100))
this.showProgress = true
}
})
.then(response => {
console.log(`上传成功!文件地址为:${response.data}`)
})
.catch(error => {
console.log(error)
})
},
downloadFile () {
axios({
url: `/api/download/${this.fileName}`,
method: 'GET',
responseType: 'blob',
onDownloadProgress: (progressEvent) => {
this.progress = parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100))
this.showProgress = true
}
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', `${this.fileName}`)
document.body.appendChild(link)
link.click()
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
```
注意:上述代码仅供参考,实际情况中需要根据自己的需求进行调整。
阅读全文