首頁  >  文章  >  web前端  >  如何使用 Window.fetch() 下載檔案並處理授權?

如何使用 Window.fetch() 下載檔案並處理授權?

Barbara Streisand
Barbara Streisand原創
2024-10-23 07:32:01612瀏覽

How to Download a File with Window.fetch() and Handle Authorization?

使用window.fetch() 下載檔案

嘗試使用window.fetch() 下載檔案時,then 區塊中要執行的適當步驟是如下所示:

.then((response) => {
  // Convert the response to a blob.
  return response.blob();
})
.then((blob) => {
  // Create a URL for the downloaded file.
  const fileURL = URL.createObjectURL(blob);

  // Navigate to the file URL to start downloading the file.
  window.location.assign(fileURL);
});

要獲得僅使用fetch API 的更簡潔、高效的解決方案,請考慮以下程式碼:

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);
  });

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

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