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

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

Linda Hamilton
發布: 2024-10-23 07:29:01
原創
502 人瀏覽過

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

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