Home >Web Front-end >JS Tutorial >How to Download Files with window.fetch() in Client-Side Applications?
Downloading Files with Window.fetch() in Client-Side Applications
When dealing with file downloads on the client side, window.fetch() provides a powerful tool for handling these operations. However, the question arises: what should be done in the then block to download a file?
Solution:
Inside the then block, the response should be processed to retrieve the file content. Here's a more concise and efficient solution that utilizes the fetch API without the need for external libraries:
<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 => { const file = window.URL.createObjectURL(blob); window.location.assign(file); });</code>
In this code, the request is made with the appropriate authentication header. The response is then converted into a blob, which represents the binary data of the file. Finally, using window.URL.createObjectURL(), a URL is generated for the blob, and the window.location.assign() is used to download the file.
By following this approach, developers can effortlessly download files from remote servers using window.fetch() in their client-side applications.
The above is the detailed content of How to Download Files with window.fetch() in Client-Side Applications?. For more information, please follow other related articles on the PHP Chinese website!