下载功能相比大家已经不陌生了吧
这都是基本常规操作啦!直接上代码
一. 文件下载
1. 先写好下载的方法
export default function getDownloadData(content, name) {
const blob = new Blob([content])
if ('download' in document.createElement('a')) {
// 非IE下载
const elink = document.createElement('a')
elink.download = name
elink.style.display = 'none'
elink.href = window.URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL对象
document.body.removeChild(elink)
} else {
// IE10+ 下载
navigator.MsSaveBlob(blob, name)
}
}
2.在页面中使用
<div @click="clickDownloadFile(item)">下载</div>
import {downloadFile} from '@/api/api.js' // 引入下载接口
import download from '@/utils/download.js' // 引入写好的下载方法
methods: {
async clickDownloadFile(file) {
let res = await downloadFile({
fileName: file.name,
url: file.url
})
if (res) {
const content = res // 接口返回文件流值
download(content, file.name)
}
}
}
3.api文件中的写法
import {axios} from '@/utils/request'
const api = {
downloadFile: '/xxxx/xxxx/download.do'
}
export function downloadFile(data) {
return axios({
url: api.downloadFile,
method: 'get',
data,
responseType: 'blob'
})
}
这样就可以实现文件的下载啦!兼容IE的写法
二. 视频的下载
这个是直接使用的链接下载,无需调用接口
downloadVideo(url, name) {
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', name)
document.body.appendChild(link)
link.click()
return this.$message.success('下载成功')
}
这就是我总结的两个下载的方法,欢迎大家提出更好的意见哦~