首頁 > web前端 > js教程 > 主體

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

Barbara Streisand
發布: 2024-10-23 07:32:01
原創
611 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!