JS 下载docx、xlsx文档

第一种

  • 请求api中的response类型必须添加responseType: "blob"(因为response回传不存在blob类型,默认字符串,会导致下载的文件无法解析)
    // 导出用户登录日志
    exportJournalLogin(params) {
        return http({
            url: `Journal/Login/Export`,
            method: 'POST',
            data: params,
            responseType: 'blob'
        })
    },
  • res 为后台返回的二进制流式文件
const blob = new Blob([res]);
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = `XX文档计算书.docx`;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
  • res 为后台返回的url
download(){
        // 这里是将链接地址url转成blob地址,fetch(url)是请求后台接口
        fetch(url).then(res => res.blob()).then(blob => { 
            const downloadElement = document.createElement('a');
            downloadElement.href = URL.createObjectURL(blob)
            // 下载文件的名称及文件类型后缀
            downloadElement.download = "小明.pdf"; 
            document.body.appendChild(link)
            link.click()
            //在资源下载完成后 清除 占用的缓存资源
            window.URL.revokeObjectURL(downloadElement.href);
            document.body.removeChild(downloadElement);
        });
            
}

第二种

    let url = window.URL.createObjectURL(new window.Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', `${this.currentRobot.name}-版本流程数据.xls`)
    document.body.appendChild(link)
    link.click()
    link.parentNode.removeChild(link)

第三种(和第一种差不多)

/**
 * 下载文件
 * res 为二进制流文件
 * item 为这条数据,包含名称即可,随机应变
 * docFormat 为文件格式,默认 MP3
 */
downloadBlob(res, item, docFormat) {
  const endFormat = docFormat || 'mp3'
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = window.URL.createObjectURL(res)
  link.download = this.$route.query.bookName + '-' + item.chapterName + '.' + endFormat
  document.body.appendChild(link)
  link.click()
  URL.revokeObjectURL(link.href) // 释放URL 对象
  document.body.removeChild(link)
},
posted @   DL·Coder  阅读(2131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示