首頁  >  文章  >  web前端  >  如何使用window.fetch()下載檔案?

如何使用window.fetch()下載檔案?

Linda Hamilton
Linda Hamilton原創
2024-10-23 07:29:01503瀏覽

How to Download Files Using window.fetch()?

使用window.fetch() 下載檔案

當使用window.fetch() API 下載檔案時,您需要連結一個then( ) 阻止fetch() 呼叫來處理響應。具體操作方法如下:

<code class="javascript">function downloadFile(token, fileId) {
  let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Authorization': token
    }
  }).then(res => {
    // Handle the response here
  });
}</code>

在then() 區塊中,您通常可以使用下列步驟來下載檔案:

  1. 將回應轉換為blob : res.blob( ).then(blob => {});
  2. 為blob 建立URL:var file = window.URL.createObjectURL(blob);
  3. 分配用於觸發下載的window.location 的URL:window.location.assign(file);

這裡有一個更短、更有效率的替代方案,只使用fetch API:

<code class="javascript">const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
fetch(url, options)
  .then(res => res.blob())
  .then(blob => {
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });</code>

以上是如何使用window.fetch()下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn