js根据文件链接下载文件

通过iframe下载

  // 移除旧的节点
  const oldNode = document.querySelector("#g-download-iframe")
  if (oldNode) {
    document.body.removeChild(document.querySelector("#g-download-iframe"))
  }
  // 生成新节点,进行下载
  const iframe = document.createElement("iframe")
  iframe.style.display = "none"
  iframe.id = "g-download-iframe"
  iframe.src = url
  document.body.appendChild(iframe)

通过a标签下载

  // 创建a标签
  const link = document.createElement("a")
  link.setAttribute("href", url)
  document.body.appendChild(link)
  // 模拟手动点击a标签下载文件
  link.click();
  setTimeout(() => {
    // 删除DOM节点
    document.body.removeChild(link)
  }, 1000);

通过window.open下载

  window.open(url, "_blank");

注意: 通过window.open方式打开链接时, 如果浏览器支持, 会在浏览器中打开该文件

posted @ 2023-02-13 16:22  青青U衿  阅读(1663)  评论(0编辑  收藏  举报