【vue项目中点击下载】弹窗提示:离开此网站?系统可能不会保存您所做的更改,改为直接下载,不提示此弹窗内容,已解决

项目中用的是window.location.href实现下载

在Web浏览器中,当尝试通过window.location.href重定向到一个文件下载URL时,浏览器通常会显示一个确认对话框,询问用户是否要离开当前页面,因为下载的文件通常是在新窗口或新标签页中打开的。这是浏览器的内置安全特性,用于防止用户无意中离开当前页面并丢失未保存的数据

downLoad(file) {
  window.location.href = `${process.env.VUE_APP_BASE_API}/common/download/resource?fileName=${file.fileName}`
}

然后就出现类似这样的弹窗提示

在这里插入图片描述

如果要直接开始下载,有两种写法,实现思路是一样的,创建a连接,设置download属性

downLoad(file) {
   //  使用<a>标签并设置download属性
     const link = document.createElement('a')
      link.href = `${process.env.VUE_APP_BASE_API}/common/download/resource?fileName=${file.fileName}`
      link.download = file.fileName // 设置download属性
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
}
downLoad(file) {
      //使用XMLHttpReques,创建一个Blob对象并使用URL.createObjectURL来创建一个可以下载的链接
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `${process.env.VUE_APP_BASE_API}/common/download/resource?fileName=${file.fileName}`, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
       if (this.status === 200) {
        const blob = this.response;
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = file.fileName;
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url); // 释放URL对象
        document.body.removeChild(link);
    }
  };
       xhr.send();
       }

实测两种都可以
在这里插入图片描述

最近更新

  1. TCP协议是安全的吗?

    2024-03-17 03:20:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-17 03:20:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-17 03:20:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-17 03:20:03       18 阅读

热门阅读

  1. transformer注意力权重系数绘图

    2024-03-17 03:20:03       20 阅读
  2. vue数据

    vue数据

    2024-03-17 03:20:03      14 阅读
  3. 以太坊的扩容方案之二层网络 L2-Rollup & zkEVM

    2024-03-17 03:20:03       18 阅读
  4. linux让前台正在执行的命令转入后台并nohup的方法

    2024-03-17 03:20:03       20 阅读
  5. 动态规划 Leetcode 96 不同的二叉搜索树

    2024-03-17 03:20:03       21 阅读
  6. CSV Excel乱码问题 和 BOM标记

    2024-03-17 03:20:03       20 阅读
  7. SpringBoot之yml与properties配置文件格式的区别

    2024-03-17 03:20:03       19 阅读
  8. gazebo_ros和ros_ign_gazebo

    2024-03-17 03:20:03       17 阅读
  9. python calendar内置日历库函数方法

    2024-03-17 03:20:03       17 阅读
  10. python企业编码管理的程序(附源码)

    2024-03-17 03:20:03       20 阅读