当使用 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() 块中,您通常可以使用以下步骤来下载文件:
这里有一个更短、更高效的替代方案,仅使用 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中文网其他相关文章!