When attempting to download a file using window.fetch(), the appropriate steps to take within the then block are as follows:
.then((response) => { // Convert the response to a blob. return response.blob(); }) .then((blob) => { // Create a URL for the downloaded file. const fileURL = URL.createObjectURL(blob); // Navigate to the file URL to start downloading the file. window.location.assign(fileURL); });
For a more concise and efficient solution using only the fetch API, consider the following code:
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); });
The above is the detailed content of How to Download a File with Window.fetch() and Handle Authorization?. For more information, please follow other related articles on the PHP Chinese website!