如何使用客户端获取下载文件
开发 Web 或移动应用程序时,您可能需要从远程服务器到用户的设备。随着 Fetch API 的引入,在客户端下载文件变得更加容易。
考虑以下代码片段:
<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(...); }</code>
在这个场景中,您有一个 Fetch 请求定义从 Google Drive 检索文件。问题出现了:您应该在 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>
此代码片段使用适当的 URL 和授权标头初始化 Fetch 请求。然后,它使用 res.blob() 方法检索文件的二进制数据。然后,它为文件创建一个临时对象 URL,并将其分配给 window.location 以触发下载。
以上是如何使用客户端 Fetch API 下载文件?的详细内容。更多信息请关注PHP中文网其他相关文章!