User uploaded file to google drive via javascript? - javascript

I have a web app that I would like the user to be able to add a file from their computer and upload it to my google drive. I have the choose file button working but I'm not sure as to how the function should look to access my google drive account and send the file upon a button click.
<h4>Upload a file:</h4>
<div class="form-group">
<input type="file" id="fileInput" name="fileInput"/>
</div><br>
I put this inside a infowindow and I'm able to search for and select a file from the user's computer.
I really just looking for the JS function to send it to my google drive.
Any help would be appreciated.

We had the same problem - and therefore developed a web service for anonymous uploading into the website owner's Google Drive.
See https://driveuploader.com/
You can easily create a reliable upload component, which can be embedded in any website with an iframe code, similarly like YouTube - or used as a part of other applications with a basic JavaScript API with webhooks.
After you create the uploader - embedding is done with the code like:
<iframe src="https://driveuploader.com/upload/{uploader key}/embed/"></iframe>
It runs in all latest web browsers - and supports unlimited file size uploads (tested on files with hundreds of gigabytes, yes GIGABYTES).
Because the component is responsive - it is perfect also for Wordpress or Google Sites websites.
If you need only a basic page where your friends, students, colleagues can securely drop into your Google Drive some (possibly large) files, then this is offered too - and completely for free.
Disclaimer: we are developers of this service.

You can find all the information you need and then some in Google's API reference but I've copied the important stuff for upload below. However, you will definitely need to look at their information regarding authentication which can be found at this link: https://developers.google.com/api-client-library/javascript/start/start-js . I have also included their authentication example below.
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
var clientId = '837050751313';
var apiKey = 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM';
var scopes = 'https://www.googleapis.com/auth/plus.me';
function handleClientLoad() {
// Step 2: Reference the API key
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
// Step 3: get authorization to use private data
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('plus', 'v1').then(function() {
// Step 5: Assemble the API request
var request = gapi.client.plus.people.get({
'userId': 'me'
});
// Step 6: Execute the API request
request.then(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.result.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.result.displayName));
document.getElementById('content').appendChild(heading);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
});
}
</script>
// Step 1: Load JavaScript client library
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
One you have authentication set up the code below is how you can upload a document. You can also use a 'PUT' request. See this link for more information: https://developers.google.com/drive/web/manage-uploads
POST /upload/drive/v2/files?uploadType=media HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Content-Length: number_of_bytes_in_file
Authorization: Bearer your_auth_token

Related

Google-map API giving Failed to load resource: the server responded with a status of 403 ()

Currently I'm working on a location project using Angularjs, where I'm using google maps JavaScript api to load maps, and for google autocomplete service. I have downloaded the JS from http://maps.googleapis.com/maps/api/js and place in the project js folder.
I have created the directive and the code is as below:
.directive('callerLocation', function(){
return {
restrict:'E',
replace:true,
scope: {callerLocation:'='},
template: '<input id="caller_location" name="caller_location" type="text"/>',
link: function($scope, elm, attrs){
var autocomplete = new google.maps.places.Autocomplete($("#caller_location")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
$scope.callerLocation=place.formatted_address;
$scope.$apply();
});
}
}
})
and accessing this is the html using the below code
<caller-location caller-location=caller_location class="form-control"></caller-location>
It work for 3-4 days and after that it is giving access forbidden issue.
and i am including the js as below in the application.(address.js contains js from http://maps.googleapis.com/maps/api/js )
module.exports = {
client: {
lib: {
js: [
'public/lib/google/address.js'
]
}
}
}
had the same problem after I had enabled rocketloader through Cloudflare. Disabling Rocketloader brought the site back to working order.
HTTP status 403 stands for "Access Forbidden". Did you make sure to apply for an access token and use that token properly? This problem most probably arises due to a misconfigured token.
If you have signed up of an API key on the Google API Console, you need to embed the script as:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

How to authenticate with Evernote developer account with OAuth.io

I have a task to create SPA that will be using Evernote account data. For authetication I want to use Oauth.io service.
"Try auth" button from Oauth.io site works fine. I see popup with prompt to sign in.
In my app html I have a simple button:
<button id="login-evernote-btn" type="button" class="bx-button bx-button-accept" onclick="app.loginWithEvernote();"><i class="fa fa-sign-in"></i> Evernote Login</button>
and my JS application:
//Constructor
function Application() {
OAuth.initialize('HERE_PASTE_MY_PUBLIC_KEY');
};
/*----------------------------*/
/* Application methods */
/*----------------------------*/
Application.prototype.loginWithEvernote = function() {
OAuth.popup('evernote', function(error, success){
});
};
// Create application Object
app = new Application();
But after clicking on my button I see splash window that closing in second. I can't enter my credentials.
What step I am doing wrong?
After successful authetication I want to use Evernote API to list all notes.
You need to log the error to see what is the problem with the popup. That maybe the domain whitelist or using 'evernote' provider instead of 'evernote_sandbox'
According evernote-sdk-js on github, you can use your token this way
Application.prototype.loginWithEvernote = function() {
OAuth.popup('evernote').done(function(evernote) {
var client = new Evernote.Client({token: evernote.oauth_token});
var noteStore = client.getNoteStore();
notebooks = noteStore.listNotebooks(function(err, notebooks) {
// run this code
});
}).fail(function(e) {
console.error(e)
});
};

Can't revoke Google API App Permissions [WEB]

I'm creating a Web App that allows users to sign in using their Google Account credentials. I'm using the Google Sign In API to do this.
So far, users can sign in and sign out and grant my app the required permissions. All good. However, I want to give my users the option to disassociate their google account with my app and destroy any data belonging to them.
I've looked through the documentation (https://developers.google.com/identity/sign-in/web/disconnect), and it only suggests this;
var revokeAllScopes = function() {
auth2.disconnect();
}
This doesn't seem to do anything. I can still sign in and sign out without needing to request any permissions for the App again. Am I missing something here, or is my understanding of how this works way off?
Here is the code for signing in and signing out;
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Sign out
Revoke Scopes
<script>
var revokeAllScopes = function() {
auth2.disconnect();
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
Any help would be much, much appreciated.
I found my mistake. I forgot I had declared the auth2 variable within the signout function, and therefore it wasn't available in the removeAllScopes function. My bad.

In Meteor, how to only load a javascript when the user is logged in using an particular external service?

What I really need is to load google apis client library for javascript when a user is logged in using google service. If a user is logged in using password or other external services, the library is not loaded.
Is this possible by any means?
Thanks.
If you want to load the library from an external URL after the user has logged in, you could try something like this (put this anywhere in your client code):
Tracker.autorun(function(c) {
var user = Meteor.user();
// replace this with the appropriate check for a google account
if (user && user.profile && user.profile.isGoogle) {
// stop the autorun now that the user is logged in
c.stop();
// load the api library
$.ajax({
url: '//url-to-fancy-google-api.google.com',
dataType: 'script',
cache: true
});
}
});
It is possible, use anti:modules package. First add it to the app:
meteor add anti:modules
Then create /layers folder inside your project and place your optional files in its subfolder:
/
layers
googleUser
someFile.module.js
anotherFile.module.js
...
Then in your code create a global module:
theApp = Module('$global').as('myApp');
and load it when necessary:
theApp.require('googleUser', function () {
console.log('googleUser code loaded');
});

How to authenticate with Google via OAuth 2.0 in a popup?

Sorry for a big edit. I am starting over as I am not stating my question correctly.
I am trying to write a client side app in HTML5. I do not want it to be hosted on a website. I am not even sure this is possible, I am fairly new to this type of application.
Anyway, I want to access Google services, which requires authenticate such as OAuth. Being that it is javascript, it sounds like OAuth2 is what I need.
I am trying to open up the google authentication in a popup (I have this part), let the user allow access, and then pass flow back to my application which can then query Google services. Problem is either 1. it asks the user to copy/paste a token into the app whenever I use response_type=code, but if I use response_type=token it requires that I redirect back to a valid URL which, since this is not hosted on a webserver, there is none.
So how can I use OAuth, and let the user grant access seamlessly?
You should have some Redirect URL defined for Google to redirect to after the authentication is done. If you cant host your pages on any web site, you can very well host it in local host.
Regarding getting the access token from the popup to the main parent window, you can setup a timer in parent window which keeps on checking the document location of the popup. Once the document location matches the Redirect URL, u can parse the access token which will will be in the URL itself.
I wrote a tutorial on exactly the same problem (using local host) yesterday and here is the link:
http://www.gethugames.in/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html
Hope you will find it useful.
To avoid a potential click jacking, Google authentication forces you to go to a full page login. I don't think you can control that.
EDIT after comment, here is a code extracted from the Google OAuth2 page that does it:
<body>
<a href="javascript:poptastic('https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token');">Try
out that example URL now</a>
<script>
function poptastic(url) {
var newWindow = window.open(url, 'name', 'height=600,width=450');
if (window.focus) {
newWindow.focus();
}
}
</script>
</body>
I believe you can use google api (gapi) for Oauth in Javascript.
Here is the documentation: Authentication using the Google APIs Client Library for JavaScript
You will not require the user to copy/paste any codes and you will not require to provide a redirect uri
All you need to do is: Go to your project in Google Developers Console and generate the following:
1. Generate new Client Id and choose options 'Installed Application' and 'Other'.
2. Generate a Public API Key
Sample Code from the above documentation:
// Set the required information
var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/plus.me';
// call the checkAuth method to begin authorization
function handleClientLoad() {
gapi.client.setApiKey(apiKey); // api key goes here
window.setTimeout(checkAuth,1);
}
// checkAuth calls the gapi authorize method with required parameters
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); // scope and client id go here
}
// check that there is no error and makeApi call
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
makeApiCall();
}
}
// API call can be made like this:
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.displayName));
document.getElementById('content').appendChild(heading);
});
});
}
I've written a mini JS library for the task, take it and see if it works for you.
https://github.com/timdream/wordcloud/blob/6d483cd91378e35b54e54efbc6f46ad2dd634113/go2.js
I am recently developing another project that rely on the same script, so I am isolating this one into an independent library project ... check the progress follows (if there are).

Categories

Resources