vue实现下载视频
使用 axios 和 Blob 对象下载视频
在 Vue 项目中通过 axios 获取视频流数据,利用 Blob 对象和 URL.createObjectURL 生成下载链接。
// 在 methods 中定义下载方法
downloadVideo() {
axios({
url: '视频URL地址',
method: 'GET',
responseType: 'blob'
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'video.mp4')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
}
使用 FileSaver.js 库简化下载
安装 FileSaver.js 库可以更简洁地实现文件下载功能。
npm install file-saver
import { saveAs } from 'file-saver'
downloadVideo() {
axios.get('视频URL地址', {
responseType: 'blob'
}).then(response => {
saveAs(new Blob([response.data]), 'video.mp4')
})
}
处理大文件分片下载
对于大视频文件,可以实现分片下载以提高可靠性和用户体验。
async downloadLargeVideo() {
const chunkSize = 1024 * 1024 // 1MB分片
let startByte = 0
let endByte = chunkSize
const videoSize = await this.getVideoSize()
while(startByte < videoSize) {
const chunk = await this.fetchVideoChunk(startByte, endByte)
// 处理分片数据
startByte = endByte
endByte = Math.min(endByte + chunkSize, videoSize)
}
}
getVideoSize() {
return axios.head('视频URL地址').then(res => {
return parseInt(res.headers['content-length'])
})
}
fetchVideoChunk(start, end) {
return axios.get('视频URL地址', {
headers: { 'Range': `bytes=${start}-${end}` },
responseType: 'blob'
})
}
添加下载进度显示
通过 axios 的 onDownloadProgress 回调可以显示下载进度。
downloadWithProgress() {
axios.get('视频URL地址', {
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
console.log(percentCompleted + '%')
}
}).then(response => {
saveAs(new Blob([response.data]), 'video.mp4')
})
}
处理跨域问题
如果视频资源存在跨域限制,需要在服务器端配置 CORS 或使用代理。
// vue.config.js 配置代理
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://视频源域名',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
注意事项
视频下载功能需要考虑版权问题,确保有合法授权 大文件下载时建议添加分片和断点续传功能 移动端浏览器可能有不同的下载行为,需要测试兼容性 某些浏览器可能会阻止自动下载,需要用户交互触发







