首頁  >  文章  >  web前端  >  如何使用客戶端 Fetch API 下載檔案?

如何使用客戶端 Fetch API 下載檔案?

Patricia Arquette
Patricia Arquette原創
2024-10-23 07:28:29917瀏覽

How Can I Download a File Using the Client-Side Fetch API?

如何使用客戶端取得下載檔案

開發 Web 或行動應用程式時,您可能需要從遠端伺服器到使用者的裝置。隨著 Fetch API 的引入,在客戶端下載檔案變得更加容易。

考慮以下程式碼片段:

<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(...);
}</code>

在這個場景中,您有一個 Fetch 請求定義從 Google Drive 擷取檔案。問題出現了:您應該在 then 區塊中做什麼來下載檔案?

下面示範了更乾淨、更有效率的檔案下載方法,利用 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>

此程式碼片段使用適當的 URL 和授權標頭初始化 Fetch 要求。然後,它使用 res.blob() 方法檢索檔案的二進位資料。然後,它為檔案建立一個臨時物件 URL,並將其指派給 window.location 以觸發下載。

以上是如何使用客戶端 Fetch API 下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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