Upload to cloud cloud google using json api from javascript

I am trying to use gapi to upload an image to google cloud storage. The current code has

 <script src="https://apis.google.com/js/api.js"></script> <script type="text/javascript"> var imgData = null; function getImage() { navigator.camera.getPicture(onSuccess, onFailure, { destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }); function onSuccess(imageURI) { imgData = encodeImageUri(imageURI); var contentLen = imgData.length; gapi.load('client', start); } function onFailure(message) { alert("Get image failed: " + message); } } function start() { // 2. Initialize the JavaScript client library. console.log('firing google storage api'); gapi.client.init({ 'apiKey': 'XXX-XX' }).then(function() { // 3. Initialize and make the API request. console.log('api initialized'); var request = gapi.client.request({ 'path': 'https://www.googleapis.com/upload/storage/v1/b/visionapibucket/o?uploadType=media&name=myObject', 'method': 'POST', 'headers': { 'Content-Type': 'image/jpeg' }, 'body': imgData }); try { //Execute the insert object request console.log('executing call'); request.execute(function(resp) { alert(resp); }); } catch (e) { console.log('An error has occurred: ' + e.message); } }).then(function(response) { console.log(response.result); }, function(reason) { console.log('Error: ' + reason.result.error.message); }); }; </script> 

I see the code beats the statement in the console: api initialized

but I don't see gapi.client.request called or even printing any error, etc.

I'm not sure what is wrong here. Please inform

+6
source share
1 answer

You cannot upload files to Google storage using only the API key. You must have an oauth token.

If the request requires authorization (for example, a request for individual private data), then the application must provide an OAuth 2.0 token with the request. An application may also provide an API key, but this is not required.

If the request does not require authorization (for example, a request for public data), then the application must provide either an API key or an OAuth 2.0 token, or any option that is most convenient for you.

https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing

In your case, you want to load, so you should have an oauth token.

You have several ways:

Learn more about the gcloud utility and download it: https://cloud.google.com/sdk/

+1
source

Source: https://habr.com/ru/post/1013848/


All Articles