Reputation: 11
I'm using this code snippet from gDrive SDK for javascript to download file :
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
How can i prompt the browser to open the download window when the ajax request is done. How to make the callback function in order to open the dialog for saving the file locally ?
Upvotes: 0
Views: 157
Reputation: 22306
Unfortunately, your approach won't work.
Because of standard browser security constraints, you can't save a file from Javascript.[1]
What you need to do is use the downloadUrl in a new window or src for an iframe to cause the browser to download the file, and prompt the user to save it. You will need to add
&access_token=ya29.YOURACCESSTOKENHERE
to the URL to avoid a 401 error.
Notes 1. Yes I know that HTML5 is starting to support limited filesystem access from Javascript, but (1) it's not widely available, (2) has restrictions on where the file can be saved, and (3) isn't the UX that the OP was asking for.
Upvotes: 1