前端實現文件下載所有方式


一.a標簽完成

<a href="文件鏈接" download='下載文件名'></a>
<--!但是其中的download對應音頻文件和視頻文件無效-->

二.js實現下載

<script>
    const a = document.createElement('a');
    a.setAttribute('href', '文件鏈接');    //a.href='文件鏈接'
    a.setAttribute('download', '文件名');   //a.download='文件名'
    a.click();
</script>

三.js中ajax實現音頻或者視頻不跳轉進行文件下載

寫代碼的思路

先請求音頻的鏈接,再把返回值轉換成二進制,再根據他二進制對象生成新鏈接,再創建a標簽,點擊a標簽

//這是vue里面的寫的普通頁面也差不多
<script>
    this.$axios({
    method: 'get',
    url: row.src,
    responseType: 'blob'  //這個不能少,讓response二進制形式,如果你按照網上教程不設置這個將返回值進行BLOB([])進行處理可能會出現解析錯誤
}).then(response => {
    const href = URL.createObjectURL(response.data); //根據二進制對象創造新的鏈接
    const a = document.createElement('a');
    a.setAttribute('href', href);
    a.setAttribute('download', row.title);
    a.click();
    URL.revokeObjectURL(href);
}
</script>

四.fetch實現

//原理和ajax一模一樣
function request() {
  fetch('<接口地址>', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: '<請求參數:json字符串>',
  })
    .then(res => res.blob())
    .then(data => {
      let blobUrl = window.URL.createObjectURL(data);
      download(blobUrl);
    });
}
 
function download(blobUrl) {
  const a = document.createElement('a');
  a.download = '<文件名>';
  a.href = blobUrl;
  a.click();
}
 
request();


免責聲明!

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



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