前端html文件下載,同源與異源下載

屬性說明
download 下載的資源的名稱
target 打開該連接的方式( _self_blank
href 資源的地址(本地、遠程地址)

a標籤跳轉

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>這是一個a標籤下載頁面</title>
</head>
<body>
<a href="http://127.0.0.1/html/pg.jpg">下載</a>
</body>
</html>

a標籤下載

  • 需要在 href 屬性中添加需要下載的文件的地址
  • download 屬性用於設置下載的文件的名稱

download不給值,會使用默認的文件名。

該屬性也可以設置一個值來規定下載文件的名稱。所允許的值沒有限制,瀏覽器將自動檢測正確的文件擴展名並添加到文件 (.img, .pdf, .txt, .html, 等等)。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>這是一個a標籤下載頁面</title>
</head>
<body>
<a href="http://127.0.0.1/html/pg.jpg" download="123.jpg">下載</a>
</body>
</html>

不同源地址下載

參考:https://www.jianshu.com/p/461b2b888a21

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>這是一個a標籤下載頁面</title>
</head>
  <body>
    <button onclick="onDownload('https://img.zcool.cn/community/02of0fe3hmj6wgj5pdbe8h3237.png','cheng_boy.png')">下載(跨域)</button>

    <script type="text/javascript">
// filepath: 圖片鏈接
// filename: 需要下載的圖片名稱
function onDownload(filepath, filename) {
      const x = new XMLHttpRequest()
      x.open('GET', filepath, true)
      x.responseType = 'blob'
      x.onload = function () {
        const blob = x.response
        const url = window.URL.createObjectURL(blob)
        // 判斷是否是IE瀏覽器
        if (window.navigator.msSaveBlob) {
          try {
            window.navigator.msSaveBlob(blob, filename)
          } catch (e) {}
        } else {
          const a = document.createElement('a')
          a.href = url
          a.download = filename
          a.click()
        }
      }
      x.send()
    }
    </script>
  </body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章