前端js实现的文件下载代码案例
function downloadFileWithBuffer(data, name, type) {
var blob = new Blob([data], {
type: type || ''#这里可以指定不同MIME 类型
})
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob) // 创建下载的链接
downloadElement.href = href
downloadElement.download = name // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
}
function downloadExcelWithResData(res) {
console.log('downloadExcelWithResData',res);
let fileName = res.headers['content-disposition'].split('filename=')[1]
if (!fileName) {
fileName = res.headers['content-disposition'].split('UTF-8\'\'')[1]
}
fileName = fileName ? fileName.replace(/\"/g, '') : 'file.xlsx'
fileName = decodeURI(fileName) || ''
downloadFileWithBuffer(res.data, fileName, 'application/vnd.ms-excel;charset=utf-8')
}
相关文章