This question already has answers here:
get file content of google docs using google drive API v3
(3 answers)
Closed 11 months ago.
I am using react-google-drive-picker to select a file from GDrive in my NextJS app. Once I have picked a file and retrieved the meta information, what is the suggested way to download or just retrieve the file content? What API is suggested to use authResponse to authenticate?
I am using:
useEffect(() => {
// do anything with the selected/uploaded files
if (data) {
var file = data.docs[0]
var xhr = new XMLHttpRequest();
xhr.open('GET', file['url']);
xhr.setRequestHeader('Authorization', 'Bearer ' + authResponse['access_token']);
xhr.setRequestHeader('Content-Type', 'application/vnd.google-apps.document');
xhr.onload = function () {
var content = xhr.responseText
console.log(content)
};
xhr.onerror = function () {
console.log("ERROR LOADING THE FILE")
};
xhr.send(JSON.stringify({"alt" : "media"}));
}
}, [data])
but the text of the document is not present in the response...
following the suggestion by #Gonzalo-Matheu, here's a way to obtain the text after picking a file with react-google-drive-picker in nextjs:
var file = data.docs[0]
var xhr = new XMLHttpRequest();
var url = 'https://www.googleapis.com/drive/v3/files/' + file['id'] + '/export?mimeType=text%2Fplain&key=' + process.env.NEXT_PUBLIC_GOOGLE_API_KEY
xhr.open('GET', URL);
xhr.setRequestHeader('Authorization', 'Bearer ' + authResponse['access_token']);
xhr.onload = function () {
var value = xhr.responseText
// do what you need with file content
console.log(value)
};
xhr.onerror = function () {
console.log("ERROR LOADING THE FILE")
};
xhr.send();
Related
i have integrated and try to use the google picker api
google picker api
but can i turn the callback into file ?
so i can upload the file to my server
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id; alert('The user selected: ' + fileId);
}
}
Once you have the fileId, you can download the file as explained in the documentation for Download files with the Drive API
Unfortunately, there is no sample for Browser Javascript, but you use e.g. XML HttpRequests.
Sample:
//provided you already have the following line from previous steps:
oauthToken = authResult.access_token;
var doc = data[google.picker.Response.DOCUMENTS][0];
var mimeType = doc[google.picker.Document.MIME_TYPE];
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/drive/v3/files/"+fileId+'?alt=media', true);
xhr.setRequestHeader('Authorization','Bearer '+oauthToken);
xhr.responseType = 'arraybuffer'
xhr.onload = function(){
var base64 = 'data:' + mimeType + ';base64,' + base64ArrayBuffer(xhr.response);
//now you have the file content as binary data (ArrayBuffer) - proceed as desired
}
xhr.send();
Note:
you can modify xhr.responseType to e.g. blob or another responseType depending on your situation.
Alternatively you could also perform a Fetch request to 'https://www.googleapis.com/drive/v3/files' to obtain the file blob.
I'm trying to use the PlayCanvas OAuth and CORS to request an image from a service via HTML request. as I understood the response return a JSON holding the data, and in this question I just want to save the path in the JSON to a .txt file located in the PlayCanvas Assets.
I'm not 100% sure about my code.
I haven't found how to grab the .txt into the JS script (it cannot be attached to an object)
will appreciate help with both
URL is
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
I've tried to use an async request like the example appearing here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
in the 'createCORSRequest':
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
xhr.onload = function (e) {
if (xhr.readyState === 46) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
I tried to place the 'stringify' and 'download' commands in initialize (moved then inside the callback
and finally ended up with what's appearing here
var Https = pc.createScript('https');
var token = 'That's the PlayCanvas Token';
var request = 'curl -H "Authorization: Bearer '+token+'" ';
var ts_URL ='https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png';
// initialize code called once per entity
Https.prototype.initialize = function() {
var url = request+ts_URL;
// ref: curl -H "Authorization: Bearer nesgdxhiqe7hylfilr6ss1rds0gq1uj8" https://playcanvas.com/api/...
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
};
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
if(method=="GET")
{
loadFile(url, DownloadToText(xhr));
}
// else... all the other cases
return xhr;
}
function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call(arguments, 2);
xhr.onload = xhrSuccess;
xhr.onerror = xhrError;
xhr.open("GET", url, true);
xhr.send(null);
}
function DownloadToText (ans)
{
JSON.stringify(ans);
download(ans, 'json.txt', 'text/plain');
}
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
function xhrSuccess() {
this.callback.apply(this, this.arguments);
}
function xhrError() {
console.error(this.statusText);
}
expected results: I expected a json.txt file to be downloaded with the URL of the image inside.
Actual results: when I launched the program and went to console, saw the image 1.png got a 404 Not Found error.
the json.txt was downloaded with '[object XMLHttpRequest]'.
Also
in the F12 i got that the link leading to the error is
https://launch.playcanvas.com/curl%20-H%20%22Authorization:%20Bearer%---theToken---%22%20https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png
while simply
https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/1.png leads to the image.
but i can't get away from the prefix if i wanna pass through the OAuth.. which is why i don't understand what was i'm doing wrong.
I am posting some data to server through Backbone.js and server sends a csv file as response. As Backbone.js handles only json format can some body tell me how to handle this case, so that i would be able to download the csv file gracefully.
object = {};
object.c1 = formObj.c1
hash = {
success: function(model, response, options) {
},
error: function(model, response, options) {
return console.log(response);
}
};
model = new P.models.mine(object);
model.doSomething(object, hash);
It always comes to error part.
The ideal way to handle this would be to change your back end code to return JSON, or create another route that returns JSON. Since you are asking this question I'm assuming that isn't an option for you.
Basically you are going to have to parse the CSV on the client side:
https://stackoverflow.com/a/1293163/944006 - Should get you started.
If you are asking to download a csv file, then just pointing the browser at the location should prompt the user for download. You cannot prompt a file download through ajax(for good reason), but there are ways to tiptoe around this limitation:
https://stackoverflow.com/a/9970672/944006
You could also use plain javascript rather than Backbone.js. Believe me this is the best way.
Here is some code:
var xhr = new XMLHttpRequest();
xhr.open('POST', Urls.download, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function (e) {
if (this.status == 200) {
var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.id = "a" + new Date().getTime();
a.setAttribute("data-bypass", "");
a.href = downloadUrl;
a.download = "list_" + new Date().getTime() + ".xlsx";
document.body.appendChild(a);
a.click();
} else {
alert('Unable to download excel.')
}
};
xhr.send(JSON.stringify(this.obj));
I use function from this Google API JS sample
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);
}
}
I get file content, but how i can create Blob from xhr.responseText ?
I found answer here http://www.html5rocks.com/ru/tutorials/file/xhr2/
I had to use
xhr.responseType='blob'
Try to use native Blob constructor.
Example form MDN:
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
This is probably a dumb question, but I am new to Web programming. I am trying to communicate with the Google Drive using client side JavaScript and CORS. I first used the jsclient library and that worked fine:
request = gapi.client.drive.files.list( {'q': " trashed = false " } );
Using CORS, my code looks like:
var xhr = new XMLHttpRequest();
xhr.open('GET','https://www.googleapis.com/drive/v2/files');
var mysearch = encodeURIComponent("q=trashed=false");
xhr.open('GET',"https://www.googleapis.com/drive/v2/files?" +mysearch,true);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() { handleResponse(xhr.responseText); };
xhr.onerror = function() { handleResponse(null); };
xhr.send();
I have tried:
var mysearch = encodeURIComponent("q=trashed=false");
var mysearch = encodeURIComponent("trashed=false");
var mysearch = encodeURIComponent("q='trashed=false'");
They all return the list of all the files. If I don't have a search string, I also get all the files.
I would like to have other search parameters also, using &, but I can't get just one to work.
How do I format the mysearch string?
Encode only the value part of the parameter:
var url = 'https://www.googleapis.com/drive/v2/files?q=' + encodeURIComponent("'trashed=false'")