Home >Web Front-end >JS Tutorial >How to Download Files Using window.fetch() in Client-Side Code
Downloading Files Using window.fetch()
In the client-side code snippet you provided, you can complete the then block to download a file as follows:
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 => res.blob()).then(blob => { // Create a URL for the Blob and assign it to the window location var file = window.URL.createObjectURL(blob); window.location.assign(file); }); }
This code offers a more efficient and library-free solution compared to using external libraries. It leverages the window.fetch() API to retrieve the file from the provided URL. The res.blob() method converts the response into a Blob object, representing the file data.
Next, we create a URL for the Blob using window.URL.createObjectURL() and assign it to the window.location property. This initiates a download action for the file, without the need for additional libraries or complex processing.
The above is the detailed content of How to Download Files Using window.fetch() in Client-Side Code. For more information, please follow other related articles on the PHP Chinese website!