ホームページ  >  記事  >  ウェブフロントエンド  >  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);
});

フェッチ 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。