How can I download a file using window.fetch?
I temporarily solve this problem by using download.js and blob
.
let download = require('./download.min');
...
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(function(resp) {
return resp.blob();
}).then(function(blob) {
download(blob);
});
}
It's working for small files, but maybe not working for large files. I think I should dig Stream more.
EDIT: syg answer is better. Just use downloadjs library.
The answer I provided works well on Chrome, but on Firefox and IE you need some different variant of this code. It's better to use library for that.
I had similar problem (need to pass authorization header to download a file so this solution didn't helped).
But based on this answer you can use createObjectURL
to make browser save a file downloaded by Fetch API.
getAuthToken()
.then(token => {
fetch("http://example.com/ExportExcel", {
method: 'GET',
headers: new Headers({
"Authorization": "Bearer " + token
})
})
.then(response => response.blob())
.then(blob => {
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = "filename.xlsx";
document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
a.click();
a.remove(); //afterwards we remove the element again
});
});
This is more shorter and efficient, no libraries only fetch API
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);
});
This solution does not allow you to change filename for the downloaded file. The filename will be a random uuid.