I tried using the example from Google Drive documentation.
So the code is :
var request = gapi.client.drive.files.delete({
'fileId' : someFileId
});
request.execute(function(resp)
{
console.log(resp);
});
The app is installed properly and I'm using drive.file scope.
The problem is that the file is not deleted. It is still present in the Drive UI and cannot be opened anymore or downloaded. File is corrupted.
The request being sent is not the DELETE https://www.googleapis.com/drive/v2/files/fileId as was stated in docs. It is a POST https://www.googleapis.com/rpc?key=API_KEY. The body contains a JSON array:
[{"jsonrpc":"2.0","id":"gapiRpc","method":"drive.files.delete","params":{"fileId":"someFileId"},"apiVersion":"v2"}]
Response contains one empty JSON object. There are no errors in the response and there are no JS errors in the page. The APIs Explorer successfully deletes the file.
Any hints?
Try a XMLHttpRequest instead:
var xmlReq = new XMLHttpRequest();
xmlReq.open('DELETE', 'https://www.googleapis.com/drive/v2/files/' + fileId + '?key=' + apiKey);
xmlReq.setRequestHeader('Authorization', 'Bearer ' + accessToken);
Related
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.
I'm trying to upload data to a file using the Google Drive v3 API by making a XMLHttpRequest.
I get the id of a file using the File Picker API which returns "0BzAI5S8IJebrUnQtYWFSVzhPdVk", so that the upload URL should be "https://www.googleapis.com/upload/drive/v3/files/0BzAI5S8IJebrUnQtYWFSVzhPdVk?uploadType=resumable".
After I make the PUT request, it returns a 404 status code with "Not Found" as the responseText.
I've tried it before and it would return with status 200 and I was able to get the Location header from the response, but now I can't get a 200 status code from any file.
Here's my code:
// Log the user in using attachClickHandler (https://developers.google.com/identity/sign-in/web/reference#googleauthattachclickhandlercontainer-options--onsuccess-onfailure)
var id = "0BzAI5S8IJebrOFVMTU5Od183Q2M";
var access_token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://www.googleapis.com/upload/drive/v3/files/' + id + '?uploadType=resumable');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.onreadystatechange = function() {
if (this.readyState == 4) console.log(this.status);
};
xhr.send();
No matter which file I choose, it always outputs 404 as the status code. I follow what it says at https://developers.google.com/drive/v3/web/resumable-upload, but it mentions nothing of why you would receive a 404 response. Any help?
Turns out I was trying to do the wrong thing. I wanted to update a file, not upload one. Instead of using "PUT", I should've been using "PATCH" as explained here. This returned a 200 response with the Location header to make the actual change.
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 using AJAX for reading data from external xml file but it is giving error "Invalid argument"
I am using IE 8
PFB the code:
var xhr;
xhr = new XMLHttpRequest();
xhr.open("GET","C:/Users/abc/Desktop/Project/POC/ajax/Data.xml", false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState===4 && xhr.status===200)
{
var items = xhr.responseXML.getElementsByTagName('name');
var output = '<ul>';
for (var i=0; i<items.length; i++)
output += '<li>' + items[i].firstChild.nodeValue + '</li>';
output += '</ul>';
var div = document.getElementById('update');
div.innerHTML = output;
}
}
xhr.send();
The line in bold is giving error.
Any idea ?
thanks in advance
you should be using url not path, like change :
xhr.open("GET","C:/Users/abc/Desktop/Project/POC/ajax/Data.xml", false);
to, something like
xhr.open("GET","http://localhost/your_Project/POC/ajax/Data.xml", false);
AJAX requests will not work for file based urls you need to host your sources on a server to make XMLHttpRequest calls
You are creating request to the server for GET for xml. but GET only understands HTTP requests so it is throwing error.
To resolve this problem you should add the xml file to the solution or web deploy directory and then make request with browser address and if successful then make it with your xhr object.
I think you should put xml file on a web server, and point your xhr target to that file url.
which looks like this:
xhr.open("GET","http://localhost/yourpath/Data.xml", false);
The basic html file, which contains your js code, should also be put on the web server too.
http://localhost/yourpath/basic.html
Because of the Same Origin Policy, you can not send a ajax request from file system to web server url, but can send the request from server A to server B, and the two servers should on same origin, both are
http://localhost
etc.
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).