I've been following this Google File Picker tutorial and I've gotten so far as to get the file picker showing and getting the URL, but I don't know how to download the file using JavaScript. If I can use VB.NET, then can someone point me in the right direction?
I've been able to download files with VB.NET from my own database, but I don't know how to get it with the Google API or with JavaScript.
All of the file picker code works, and I'm calling this from the onSelect of the FilePicker:
function downloadGDriveFile(file) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl); // use selfLink??
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function () {
var content = xhr.responseText;
};
xhr.onerror = function () {
alert('Download failure.');
};
xhr.send();
} else {
alert('Unable to download file.');
}
}
And when I click on the download URL I get this error:
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
The error you posted is an issue with your account reaching it's max usage limit. Different issue than downloading the file. I don't have any knowledge on the google file picker api, but I'm going to assume this is in the browser.
You may have to specify req.responseType = "arraybuffer" because it could default to json.
I recommend using http://danml.com/download.html. Browser API does not expose the download modal for security reasons. The hack is to create an invisible a tag set the url to the blob of the body that you received and programmatically click the tag. The library provided does exactly that.
Related
I'm trying to make an XML request inside the content.js file of a chrome extension I am making. I'm having trouble, however, making the request, and adding the appropriate event listeners. In the current configuration, the open after the listeners, the console says my request needs to be open before being sent, although you'll note that the send method is only called in the callback function when the request has been loaded. In the case that I put the open before the event listeners, the console says that the request has been aborted. If there is a better way of requesting and parsing XML data within a google chrome extension application, I would appreciate any advice. I've left the link in so you can see what type of XML data I'm dealing with.
var l = "https://video.google.com/timedtext?lang=en&v=5MgBikgcWnY";
function addScript () {
$(document).ready(function() {
$('#related').prepend('<div id="script-box" class="col s12"></div>');
$('#script-box').append('<h3 id="script-title">Quote</h3>');
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", console.log("The download is still in progress"));
xhr.addEventListener("abort", console.log("This process has been aborted"));
xhr.addEventListener("load", parseXML(xhr));
xhr.addEventListener("error", console.log("An error has ocurred."));
xhr.open('get', l, true);
});
}
function parseXML(r) {
r.send();
var result = r.responseText;
console.log(result);
}
i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.
I'd like to know if HTML5 API may fit this use case:
some videos are present on a public server (say http://videosanbox.me/video.mpg)
the JS/html5 app should store the videos locally in order to be able to play them also off-line (videos are public, there are no security
warnings)
In my initial tests I am unable to go past the "No 'Access-Control-Allow-Origin'" error.
In my understanding the following script should:
request with a get the content located at the given URL
prepare 1Mb file somewhere (I assume I'll have other errors here, but I'll get there when I'll see them:))
for now I'm interested in understanding why this error is happening, wouldn't it be normal for a client (a mobile browser) to query for resources which are not already on it?
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://videosanbox.me/video.mpg', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
window.requestFileSystem(TEMPORARY, 1024 * 1024, function(fs) {
fs.root.getFile('video.mpg', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) { alert('writing'); };
writer.onerror = function(e) { alert('error'); };
var blob = new Blob([xhr.response], {type: 'video/mpg'});
writer.write(blob);
}, onError);
}, onError);
}, onError);
};
xhr.send();
onError is just doing something in case of error: function onError(e) {console.log('Error', e);}
Solution 1
On the server side, you need this header to be passed:
header('Access-Control-Allow-Origin: *');
Unfortunately, that may not be possible if you don't have control over videosanbox.me. If not, contact them and see if they're willing to allow this. If not, don't worry, there's a second solution:
Solution 2
Create a web page on your own server and allow cross site scripting (but use security to restrict who can use this page). In that page's code, it will take the request and open an HTTP connection to http://videosanbox.me, retrieve the mpg file and spit it back to the PhoneGap app as a Blob. Your PhoneGap would connect to this page (on your server) via Ajax instead of http://videosanbox.me.
I have download documents from google drive by using Google drive API with java. But i want to use javascript instead of java. So i am using Drive API client libraries java script code.
i am using the below code for achieving this
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);
}
}
My problem is i can able to display all file names and contents. but i can't download the files. Do i need to do any extra code? How can i save the files in my local system. any suggestions ?
Note: i can get value in file.downloadUrl if i paste the downloadUrl in the browser it won't give any result ,just show a blank page.
"if i paste the downloadUrl in the browser it won't give any result" is correct because when you GET using a browser there is no authentication header. If you check the status you will see a 401 error.
I use "Authorization: 'OAuth ' + gapi.auth.getToken()['access_token']" rather than 'Bearer'. I'm not sure if that is significant.
Are you sure the downloadUrl is current? This is a short-lived attribute, so it's possible the link has expired.
It's also possible the access token is invalid. As Burcu said, your answer is probably within the response and status to your xhr get.
I am attempting to download a file from Google Storage using the Javascript json api. I am able to retreive the object info by using the code below, however I'm not sure how to get the actual media. I'm familiar with the Java library method getMediaHttpDownloader, but I do not see an equivalent in JS. Any help would be appreciated!
gapi.client.storage.objects.get({"bucket":"bucketName","object":"objectName"});
The Javascript library does not currently support directly downloading media. You can still get to the data, but you'll have to access it another way.
Depending on the domain your website is hosted on and the bucket you're reading from, you'll need to set up CORS: https://developers.google.com/storage/docs/cross-origin
Then, you'll need to request the object directly via the XML API. For example, you could do something like this:
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://'+bucket+'.storage.googleapis.com/'+object);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
I've ended up not using the api(not sure that you can download using api, interested if you do know how) and using XmlHttpRequest instead. To do this I had to setup CORS for my google storage bucket to allow my site cross domain access. Below is my code:
var myToken = gapi.auth.getToken();
var req = new XMLHttpRequest;
req.open('GET','https://storage.googleapis.com/bucket/object',
true);
req.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
req.send(null);
I did it using gapi and jQuery.
In my case object is public. (pulbic link in storage browser must be checked). In case you don't want your object to be public, use $.post instead of $.get and provide assess_token as header exactly as it is done in other answers.
Storage.getObjectInfo retrieves object metadata.
Storage.getObjectMedia retrieves object content.
var Storage = function() {};
Storage.bucket = 'mybucket';
Storage.object = 'myfolder/myobject'; //object name, got by gapi.objects.list
Storage.getObjectMedia = function(object, callback) {
function loadObject(objectInfo) {
var mediaLink = objectInfo.mediaLink;
$.get(mediaLink, function(data) { //data is actually object content
console.log(data);
callback(data);
});
}
Storage.getObjectInfo(object, loadObject);
};
Storage.getObjectInfo = function(object, callback) {
var request = gapi.client.storage.objects.get({
'bucket' : Storage.bucket,
'object' : Storage.object
});
request.execute(function(resp) {
console.log(resp);
callback(resp);
});
};
It is also relatively rare case when we need to download the content of object. In most cases objects stored in Storage are media files like images and sounds and then all what we need is actually mediaLink, which must be inserted to src attribute value of appropriate dom element (img or audio).