Home > Web Front-end > JS Tutorial > body text

How to Download Files with window.fetch() in Client-Side Applications?

DDD
Release: 2024-10-23 07:27:30
Original
613 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!