Google Storage Media download with Json api - javascript

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).

Related

difference between youtube's request and mine

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.

Get image data from another domain with AJAX request

I am trying to get binary data of an image from another domain with an AJAX request. I tried various methods, but there was no working solution. I found some code on the internet that looked good, but even with this calls I get errors.
What do I wrong? Is there a standardized way to do this?
Here is what I tried until now:
var request = this.createCORSRequest('GET', 'http://url/to/image.png');
request.onload = function () {
var text = request.response;
};
request.onerror = function (error) {
alert('Woops, there was an error making the request.');
};
request.send();
private createCORSRequest(method, url) {
var xhr: XMLHttpRequest = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
var xdhr = new XDomainRequest();
xdhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
I even found this solution without ajax here on stackoverflow, but it does not work for me:
Asynchronously load images with jQuery
Here a screen of the properties the error event contains:
My goal is to get the binary of an image from a url which I get from an atom feed . I need the binaries to copy the picture to MS SharePoint.
You cannot get data from another domain unless :
the remote server allows it using CORS
you run your browser in an unsafe mode.
Reason : otherwise site A would be able to (maliciously) read the user data from site B
You must add headers to the method to allow cross domain request.
For example, if you are trying to get data from www.example.com/main.php , then you must add headers to allow those method to be called from different domain.

google drive download document using javascript :can't download files

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.

Deleting a Google Drive file using JS client

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);

window.open with headers

Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks.
Can I control the HTTP headers sent by window.open (cross browser)?
No
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
I need some cunning hacks...
It might help if you described the problem instead of asking if possible solutions would work.
Sadly you can't control headers when doing window.open()
Nice and easy, how I managed to open a file with custom headers:
const viewFile = async (url) => {
// Change this to use your HTTP client
fetch(url, {/*YOUR CUSTOM HEADER*/} ) // FETCH BLOB FROM IT
.then((response) => response.blob())
.then((blob) => { // RETRIEVE THE BLOB AND CREATE LOCAL URL
var _url = window.URL.createObjectURL(blob);
window.open(_url, "_blank").focus(); // window.open + focus
}).catch((err) => {
console.log(err);
});
};
Download file to cache
window.open to cache
If you are in control of server side, it might be possible to set header value in query string and send it like that?
That way you could parse it from query string if it's not found in the headers.
Just an idea... And you asked for a cunning hack :)
As the best anwser have writed using XMLHttpResponse except window.open, and I make the abstracts-anwser as a instance.
The main Js file is download.js Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
You can also use an F5 load balancer, and map the cross-browser URL that you are trying to fetch to an URL inside your domain of origin.
Mapping can be something like:
companyA.com/api/of/interest----> companyB.com/api/of/interest
Assuming your domain of origin is "companyA.com" then the browser will not have any problems in sending all cookies on the header of that request, since it's towards the same domain.
The request hits the load balancer and is forwarded towards "companyB.com" with all headers responses will be sent to the from server side.
You can't directly add custom headers with window.open() in popup window
but to work that we have two possible solutions
Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in<i>window.open()</i>
here is abc.html
$.ajax({
url: "ORIGIONAL_URL",
type: 'GET',
dataType: 'json',
headers: {
Authorization : 'Bearer ' + data.id_token,
AuthorizationCheck : 'AccessCode ' +data.checkSum ,
ContentType :'application/json'
},
success: function (result) {
console.log(result);
},
error: function (error) {
} });
call html
window.open('*\abc.html')
here CORS policy can block the request if CORS is not enabled in requested URL.
You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.
Suppose in Java Servlet(/requestURL) we'll make this request
`
String[] responseHeader= new String[2];
responseHeader[0] = "Bearer " + id_token;
responseHeader[1] = "AccessCode " + checkSum;
String url = "ORIGIONAL_URL";
URL obj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Authorization", responseHeader[0]);
urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
}
in.close();
response.sendRedirect(response1.toString());
// print result
System.out.println(response1.toString());
} else {
System.out.println("GET request not worked");
}
`
call servlet in window.open('/requestURL')
Use POST instead
Although it is easy to construct a GET query using window.open(), it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:
<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>
<input type="button" onclick="loadNnextPage()" value="Click me!">
<script>
function loadNnextPage() {
document.getElementById("helper").headerData.value = "New";
document.getElementById("helper").submit();
}
</script>
Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.
Problems with GET
Query strings get stored in browser history,
can be shoulder-surfed
copy-pasted,
and often you don't want it to be easy to "refresh" the same transaction.

Categories