I'm using Google Drive API to make possible for users to upload files from their Google Drive account to my website. When I save those files I get 0 KB PDFs, 107 KB DOCs which are "moved temporarily" and so on...
GDrive JS method:
var MyGoogleDrive = function (obj) {
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'AIzaSyARiUlXRErh7NCQTv6j7YvWCuRaTCZ64S4';
// The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
var clientId = "405458969849-eqr9rrjsq5th2a0av2o3bc72adn4d8hu.apps.googleusercontent.com";
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': function(){}});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
pickerApiLoaded = true;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.DOCUMENTS);
view.setIncludeFolders(true);
view.setMimeTypes("application/pdf, image/png, image/jpeg, application/vnd.openxmlformats-officedocument.wordprocessingml.document");
/*var view1 = new google.picker.DocsView(google.picker.ViewId.DOCUMENTS);
view1.setIncludeFolders(true);
var view2 = new google.picker.DocsView(google.picker.ViewId.DOCUMENTS);
view2.setIncludeFolders(true);*/
var picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setOAuthToken(oauthToken)
.addView(view)
.addView(google.picker.ViewId.FOLDERS)
.addView(google.picker.ViewId.DOCS)
.addView(google.picker.ViewId.DOCUMENTS)
.addView(google.picker.ViewId.SPREADSHEETS)
.addView(google.picker.ViewId.DOCS_IMAGES)
.addView(google.picker.ViewId.PDFS)
.setLocale('de')
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var files = data[google.picker.Response.DOCUMENTS];
for(var i=0, l = files.length; i<l; i++){
(function(i){
$.ajax({
url: obj.url,
type: 'post',
data: 'name='+files[i].name+'&link='+files[i].embedUrl+'&provider=google',
dataType: 'json',
async: false,
success: function (data){
if(data.name){
obj.htmlBlock.add(data);
}
},
error: function(error){
alert(error.responseText);
}
});
})(i);
}
}
}
return {
init: function () {
this.$el = $(obj.el);
var self = this;
onApiLoad();
self.$el.click(function(){
onAuthApiLoad();
});
}
};
}
Response for a doc uploaded
<HTML>
<HEAD>
<TITLE>Moved Temporarily</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Temporarily</H1>
The document has moved here.
</BODY>
</HTML>
Related
I'm trying to implement Google Picker and the Google Drive API in JavaScript on my website. Currently, I use a PHP script to fetch Google Drive documents, but it's using restricted scopes and I want to remove restricted scopes from my application.
First, I got the Google Picker quickstart code working. I tried to add a Google Drive get using the access token that I fetched in the Google Picker code. Google Drive code comes over in the client.js, right? Is the access token used in api.js compatible with the access token used for client.js?
I found an old Gist from six years ago and tried to integrate and update it. Here's my code right now. The gapi.client.drive.files.get fails to get the file.
// Scope to use to access user's photos.
var scope = 'https://www.googleapis.com/auth/drive.file';
var pickerApiLoaded = false;
var driveApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth2', onAuthApiLoad);
gapi.load('picker', onPickerApiLoad);
}
function onClientLoad() {
gapi.client.setApiKey(developerKey);
gapi.client.load('drive', 'v2', onDriveApiLoad);
}
function onAuthApiLoad() {
var authBtn = document.getElementById('auth');
authBtn.disabled = false;
authBtn.addEventListener('click', function() {
gapi.auth2.init({ client_id: clientId }).then(function(googleAuth) {
googleAuth.signIn({ scope: scope }).then(function(result) {
handleAuthResult(result.getAuthResponse());
})
})
});
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function onDriveApiLoad() {
driveApiLoaded = true;
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.SPREADSHEETS);
//view.setMimeTypes("text/csv");
//view.setMode(google.picker.DocsViewMode.LIST);
view.setQuery(jQuery('[updateparam="name"]').val());
var picker = new google.picker.PickerBuilder().
//addView(google.picker.ViewId.DOCS).
addView(view).
setInitialView(view).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileId = doc[google.picker.Document.ID];
jQuery('[updateparam="googleDriveFileId"]').val(fileId);
//if (driveApiLoaded) {
var request = gapi.client.drive.files.get({
'fileId': fileId
});
request.execute(function(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.onerror = function() {
warningMessage.displayMessage('Failed to download Google Drive document ' + fileId);
};
});
//} else {
// warningMessage.displayMessage('Google Drive API has not been loaded.');
//}
}
// Triggers before Picker is shown
// else {
// warningMessage.displayMessage('No Google Drive document selected.');
//}
}
And my script tags:
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?key=KEY"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
The problem is when you try to retrieve the downloadUrl attribute in file.downloadUrl, which is a field that doesn’t exist anymore in the Drive API version 3 (It was in the version 2), check v2 [1] and v3 [2].
Instead, you should use the webContentLink attribute to download the file, which is available for files with binary content as images, pdf, etc, but not for google docs and sheets (it’s only available the webViewLink attribute which is the url to the file) [2]. For these cases (docs and sheets), you can implement the import method which works for convert google documents and returns the file object [3]. The import request would be like this:
var request = gapi.client.drive.files.import({ 'fileId': fileId, 'mimeType': mimeType });
With mimeType for the target document you want (pdf, txt, etc). Then, inside the callback, access the attribute using file.webContentLink as with the other cases.
[1] https://developers.google.com/drive/api/v2/reference/files
[2] https://developers.google.com/drive/api/v3/reference/files
[3] https://developers.google.com/drive/api/v3/reference/files/export
Through trial and error, I discovered that in order to load both the Google Picker (client:auth2) and the Google Drive API (gapi.client), the Google Picker must be initialized with a callback, and then the Google Drive API is initialized with a Promise that must be chained. If the Promise is not chained, then it will be unresolved and will not work.
// Use the Google API Loader script to load the google.picker script.
function loadPicker() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
driveApiLoaded = true;
}
function onPickerApiLoad() {
pickerApiLoaded = true;
}
function askForClientAuthorization() {
gapi.load('client:auth2', function(_) {
window.gapi.client.init({
apiKey: developerKey,
clientId: clientId,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
scope: 'https://www.googleapis.com/auth/drive.file'
})
.then(function(__) {
return gapi.client.drive.files.export({
'fileId': window.googleDriveFileId,
'mimeType': 'text/csv'
})
.then(function(file) {
// Client is authorized to access this file, do something with the file
})
.catch(function(e) {
gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
});
})
})
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
return true;
} else {
return false;
}
}
// Create and render a Picker object for searching images.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.SPREADSHEETS);
view.setMode(google.picker.DocsViewMode.LIST);
view.setQuery(window.dataFeedName);
var picker = new google.picker.PickerBuilder()
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
return picker;
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
// Do work
}
}
With this code, it must check if the user is authorized for every execution.
I am working with the Google drive Picker API, where a user select a document, and then the URL is generated as a text.
I have already enabled multi-select, where user can select multiple documents in one instance, but the problem is that I am only able to generate one URL.
Below is the code:
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/drive'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.PDFS).
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = url;
document.getElementById('result').innerHTML = message;
}
</script>
Below is the html found in the body
<div id="result"></div>
I think the issue lies below:
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = url;
document.getElementById('result').innerHTML = message;
}
I am receiving the following error:
Uncaught TypeError: Cannot read property 'urlshortener' of undefined
I am essentially trying to store into parse a url generated from google drive that has been shorten.
Below is the entire code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>upload</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult
);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = url;
document.getElementById('result').innerHTML = message;
}
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<div id="output">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular, this where I attempt to shorten the URL to store into Parse:
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
Update:
Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:
<html>
<head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script type="text/javascript">
function makeShort() {
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load() {
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"></script>
</head>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
I dug through your example and tried to see what is going on, but I opted to start fresh and try to accomplish this in a simple way. I see that you are using Angular, so I made a little fiddle to try and shorten the url to this question.
The main issue I think, is that you need to generate a new key and follow the configuration steps. I did so in minutes and it worked fine. Be sure to choose the api you want (urlshortener) in your dashboard!
Here is the link I was able to generate http://goo.gl/15yWwP
function googleOnLoadCallback() {
var key = '{ YOUR KEY }';
var apisToLoad = 1; // must match number of calls to gapi.client.load()
var gCallback = function () {
if (--apisToLoad == 0) {
//Manual bootstraping of the application
var $injector = angular.bootstrap(document, ['app']);
};
};
gapi.client.setApiKey(key);
gapi.client.load('urlshortener', 'v1', gCallback);
}
<script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
And inside my shorten() function
var request =
gapi.client.urlshortener.url.insert({
'longUrl': '{ YOUR LONG URL }'
});
request.execute(function(response) {
console.log(response.id);
});
JSFiddle link
I know how to retrieve a value from a textfield that a user has inputed, however, I want to be able retrieve the text thats outputed from the following code:
var message = url;
document.getElementById('result').innerHTML = message;
Essentially I want to store into Parse a shorten URL, where the URL is generated from the document selected in Google Drive, and then that URL is display on screen to the user, and thats the URL I want to grab to shorten.
Below is the entire code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>upload</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = url;
document.getElementById('result').innerHTML = message;
}
var longUrl=message;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<div id="output">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular, this where I attempt to shorten the URL to store into Parse:
var longUrl=message;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
Any help would be greatly appreciated
Update:
Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:
<html>
<head>
</head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
I would like to store a URL as a string into parse.
In particular, user select an item from Google drive using the Google Drive Picker, and then a URL is produced. I want to take that URL and store it into parse under a class named "Scan".
Let me better elaborate in code:
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
I have generated the url through
url = doc[google.picker.Document.URL];
and where the url is displayed as a string on the website through the following lines:
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
All i want is to store that url into parse, however, not sure how to workout this code and inserted in the my google drive picker select code as shown below:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
Any help would be greatly appreciated.
Update 2: Below is a code that has tries to integrate parse with my initial code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("Name", url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular this section,
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("Name", url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
under your
Parse.initialize("ID", "ID");
try:
var PDFUploadObject = new Parse.Object.extend("Scan");
var PDFUpload = new PDFUploadObject ();
PDFUpload.set("Name",url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});