vue实现断点下载
vue实现断点下载的方法
使用axios结合Blob对象和localStorage实现断点下载功能。关键在于记录已下载的字节位置,并在中断后恢复下载时从该位置继续。
核心代码实现
安装axios依赖:
npm install axios
在Vue组件中实现逻辑:
import axios from 'axios';
export default {
data() {
return {
downloadedSize: 0,
totalSize: 0,
isDownloading: false,
cancelToken: null
}
},
methods: {
async startDownload() {
const url = 'YOUR_FILE_URL';
const savedProgress = localStorage.getItem('downloadProgress');
if (savedProgress) {
this.downloadedSize = parseInt(savedProgress);
}
this.isDownloading = true;
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
this.cancelToken = source;
try {
const response = await axios({
method: 'get',
url: url,
responseType: 'blob',
headers: {
'Range': `bytes=${this.downloadedSize}-`
},
cancelToken: source.token,
onDownloadProgress: (progressEvent) => {
if (progressEvent.lengthComputable) {
this.totalSize = progressEvent.total;
this.downloadedSize = progressEvent.loaded;
localStorage.setItem('downloadProgress', this.downloadedSize);
}
}
});
const blob = new Blob([response.data]);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'filename.ext';
link.click();
this.resetDownload();
} catch (error) {
if (axios.isCancel(error)) {
console.log('Download canceled');
} else {
console.error('Download error:', error);
this.resetDownload();
}
}
},
cancelDownload() {
if (this.cancelToken) {
this.cancelToken.cancel();
}
this.isDownloading = false;
},
resetDownload() {
localStorage.removeItem('downloadProgress');
this.downloadedSize = 0;
this.totalSize = 0;
this.isDownloading = false;
}
}
}
关键点说明
使用Range请求头指定下载起始位置,格式为bytes=start-表示从start字节开始下载剩余部分
onDownloadProgress回调函数实时更新下载进度,并将进度保存到localStorage

下载完成后调用resetDownload清除本地存储的进度信息
取消下载时调用cancelToken.cancel()中止请求
界面实现示例
<template>
<div>
<button @click="startDownload" :disabled="isDownloading">
{{ isDownloading ? 'Downloading...' : 'Start Download' }}
</button>
<button @click="cancelDownload" v-if="isDownloading">
Cancel Download
</button>
<div v-if="totalSize > 0">
Progress: {{ (downloadedSize / totalSize * 100).toFixed(2) }}%
</div>
</div>
</template>
服务端要求
服务器需要支持Range请求头,常见的静态文件服务器如Nginx、Apache默认支持。如需自定义服务端,需实现类似以下逻辑:

app.get('/download', (req, res) => {
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
// 处理断点续传逻辑
} else {
// 普通下载逻辑
}
});
注意事项
大文件下载建议使用FileSaver.js库处理Blob保存
跨域请求需服务端配置CORS头部
下载进度显示建议添加节流处理避免频繁渲染
本地存储有大小限制(通常5MB),超大文件需考虑其他存储方案






