前端url下載視頻資源


下載url視頻有以下幾種方案:

1.a標簽download,但是這種因為瀏覽器機制會先打開預覽,圖片與視頻都是這樣。在預覽頁面右鍵下載。如果想通過a標簽直接下載,可以通過設置Nginx配置。

  

// url為資源地址
// newName為資源的原名稱
// a標簽的url a標簽的download屬性並不能修改名稱,這時候我們就需要用到nginx的一個默認配置renameto達到重置名稱的效果
const tepmUrl = url + '?renameto=' + newName

  

server {
        listen 8086;
        server_name 192.168.1.66;
        location / {
            proxy_pass http://127.0.0.1:8086;
            root html;
            index index.html index.htm;
        }
        location /image/ {
            root html/devGif;
            autoindex on;
            // 主要配置
             if ($request_filename ~* ^.*?.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|jpg|png)$){
               add_header Content-Disposition 'attachment';
            }
        //end
        }
}

  

2.通過前端二進制文件流容器,blob對象進行操作。通過xmlHttpRequest進行訪問視頻url地址,得到視頻數據后

  轉為二進制文件流保存在blob對象, 再通過createObjectURL創建一個包含二進制文件流額url,再通過創建

  a標簽設置下載地址,主動調用下載操作,進行視頻二進制文件流下載

示例代碼如下:

  function  downFile() {
      let url = 'https://xxxx.com"   
      let name = '視頻資源'
      let xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'blob' // 返回類型blob
      // 監聽進度
      xhr.onprogress = function (e) {
        if (e.lengthComputable) {
          // 文件總體積
          console.log(e.total)
          // 已下載體積
          console.log(e.loaded)
        }
      }
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let blob = this.response
          // 轉換一個blob鏈接
          let u = window.URL.createObjectURL(new Blob([blob]))
          let a = document.createElement('a')
          a.download = name
          a.href = u
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
          // 釋放
          window.URL.revokeObjectURL(u)
        }
      }
      xhr.onerror = function () {
        console.log('失敗')
      }
      xhr.send()
    },

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM