IMG-LOGO

Google Drive API using Javascript

andy - 18 Dec, 2015 76350 Views 170 Comment

You will learn how to utilize the Google API Drive completely using Javascript programming only. There will be extra javascript libraries such as JQuery and CSS for styling our Google Drive interface screen.

This tutorial will be divided into couple sections as below:

  1. Create your Google Apps project and how to enable the Google API Drive.
  2. Layout the login panel screen and browsing directories and files of your Google Drive.
  3. Adding the functionalities and features like creating folder, uploading and delete file, browse folders, show shared folders and files only, preview images in lightbox, convert uploaded file to google doc or OCR readable, show the user information and add the logout link.

1. Create your Google Apps project and how to enable the Google API Drive.

Before you start, you must have a Gmail account. If you do not have one, please register the free email first. Once you have it, please go to the following site to create a new project for our google drive api example.

https://console.developers.google.com

Once login, go to enable and manage API section and click the link.

The next step is to create the google apps project. Simply enter the project name and create it.

Once the project is created, the next step is to enable the Google Drive API. By default, this API is not enabled. You will need to search the Drive API from the list and enable this API.

Once you have enabled the Google Drive API, we then need to create the Oauth Client ID. Under the credential tab, there is an option called Create Credentials. Choose the option Oauth Client ID.

Please make sure you enter the correct javascript origins. If you are working in localhost, you enter localhost url as the address. If you are using any ports on your address, do not forget to add it as well.

Once you have setup your url origins, you are ready to go. When you download the demo files from this page, remember to change your client id you created under your account.

2. Layout the login panel screen and browsing directories and files of your Google Drive.

The next big step is to design the interface of our Google Drive API screen. The screen will consist of two interfaces, one is for the login screen and the second screen will be the Google Drive Browser screen.

This will be our simple login screen, where it will popup a window to Google login page when you click the login button and it will request a permission to our app to access your google api drive.

This is going to be our google drive user panel interface. You will see there are some texts represent on how the interface screen looks like.

Both login and user screen will be styled using CSS with some free icons. Let's started with the html interface screen code. Please see the extra libraries such as CSS and Javascript files. There are only 3 files you need to create which are google-drive.html, google-drive.css and google-drive.js, the remaining files are external libraries.

You can copy the following html source code and name it as google-drive.html.

<!DOCTYPE html>
<head>
<title>Google Drive API Javascript tutorial</title>
<link href="lightbox.css" rel="stylesheet" />
<link href="google-drive.css" rel="stylesheet" type="text/css"/>
</head>
<body>


<div id="transparent-wrapper"></div>
<div id="login-box" class="hide">
	<p>Please login on your google account.</p>
	<button id="btnLogin" onclick="handleAuthClick()" class="button">Login</button>
</div>

<div id="drive-box" class="hide">
	<div id="drive-breadcrumb">
        <span class='breadcrumb-arrow'></span> <a data-id='root' data-level='0'>Home</a>
        <span id="span-navigation"></span>
    </div>
	
    <div id="drive-info" class="hide">
        <div class="user-item">Welcome <span id="span-name"></span></div>
        <div class="user-item">Total Quota: <span id="span-totalQuota"></span></div>
        <div class="user-item">Used Quota: <span id="span-usedQuota"></span></div>
		<div class="user-item">Share Mode: <span id="span-sharemode">OFF</span></div>
        <div class="user-item"><a id="link-logout" class="logout-link" onclick="handleSignoutClick()">Logout</a></div>
    </div>
	
	<div id="drive-menu">
        <div id="button-reload" title="Refresh"></div>
		<div id="button-upload" title="Upload to Google Drive" class="button-opt"></div>
		<div id="button-addfolder" title="Add Folder" class="button-opt"></div>
        <div id="button-share" title="Show shared files only"></div>
    </div>
	<div id="drive-content"></div>
	<div id="error-message" class="flash hidden"></div>
	<div id="status-message" class="flash hidden"></div>
</div>

<input type="file" id="fUpload" class="hide"/>
<div class="float-box" id="float-box">
    <div class="folder-form">
        <div class="close-x"><img id="imgClose" class="imgClose" src="images/button_close.png" alt="close" /></div>
        <h3 class="clear">Add New Folder</h3>
        <div><input type="text" id="txtFolder" class="text-input" /></div>
		<button id="btnAddFolder" value="Save" class="button">Add</button>
		<button id="btnClose" value="Close" class="button btnClose">Close</button>
    </div>
</div>
<div id="float-box-info" class="float-box">
    <div class="info-form">
        <div class="close-x"><img id="imgCloseInfo" class="imgClose" src="images/button_close.png" alt="close" /></div>
        <h3 class="clear">File information</h3>
        <table cellpadding="0" cellspacing="0" class="tbl-info">
            <tr>
                <td class="label">Created Date</td>
                <td><span id="spanCreatedDate"></span></td>
            </tr>
            <tr>
                <td class="label">Modified Date</td>
                <td><span id="spanModifiedDate"></span></td>
            </tr>
            <tr>
                <td class="label">Owner</td>
                <td><span id="spanOwner"></span></td>
            </tr>
            <tr>
                <td class="label">Title</td>
                <td><span id="spanTitle"></span></td>
            </tr>
            <tr>
                <td class="label">Size</td>
                <td><span id="spanSize"></span></td>
            </tr>
            <tr>
                <td class="label">Extension</td>
                <td><span id="spanExtension"></span></td>
            </tr>
        </table>
		<button id="btnCloseInfo" value="Close" class="button btnClose">Close</button>
    </div>
</div>
<div id="float-box-text" class="float-box">
    <div class="info-form">
        <div class="close-x"><img id="imgCloseText" class="imgClose" src="images/button_close.png" alt="close" /></div>
        <h3 class="clear">Text Content</h3>
        <div id="text-content"></div>
		<button id="btnCloseText" value="Close" class="button btnClose">Close</button>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="date.js" type="text/javascript"></script>
<script src="lightbox.min.js" type="text/javascript"></script>
<script src="google-drive.js"></script>
<script async defer src="https://apis.google.com/js/api.js" 
      onload="this.onload=function(){};handleClientLoad()" 
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<script src="upload.js"></script>

</body>
</html>

If you see carefully on the html source code, you can see that I have included a hide class. This class is intended to hide the login and user interface panel when the page loads. All the html code is pretty straight forward. The float-box panel will be hidden by default, it will be used when you click the button and it will be displayed as a popup.

The next part is the JavaScript code. I have included the comment on each function sub heading. You can name this file as google-drive.js

/******************** GLOBAL VARIABLES ********************/
var SCOPES = ['https://www.googleapis.com/auth/drive','profile'];
var CLIENT_ID = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
var API_KEY = 'YOUR_API_KEY';
var FOLDER_NAME = "";
var FOLDER_ID = "root";
var FOLDER_PERMISSION = true;
var FOLDER_LEVEL = 0;
var NO_OF_FILES = 1000;
var DRIVE_FILES = [];
var FILE_COUNTER = 0;
var FOLDER_ARRAY = [];

/******************** AUTHENTICATION ********************/

 function handleClientLoad() {
	// Load the API client and auth2 library
	gapi.load('client:auth2', initClient);
}

//authorize apps
 function initClient() {
	gapi.client.init({
		apiKey: API_KEY, //THIS IS OPTIONAL AND WE DONT ACTUALLY NEED THIS, BUT I INCLUDE THIS AS EXAMPLE
		clientId: CLIENT_ID,
		scope: SCOPES.join(' ')
	}).then(function () {
	  // Listen for sign-in state changes.
	  gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
	  // Handle the initial sign-in state.
	  updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
	});
}


//check the return authentication of the login is successful, we display the drive box and hide the login box.
function updateSigninStatus(isSignedIn) {
	if (isSignedIn) {
		$("#drive-box").show();
		$("#drive-box").css("display","inline-block");
        $("#login-box").hide();
        showLoading();
        getDriveFiles();
	} else {
		$("#login-box").show();
        $("#drive-box").hide();
	}
}

function handleAuthClick(event) {
	gapi.auth2.getAuthInstance().signIn();
}

function handleSignoutClick(event) {
	if(confirm("Are you sure you want to logout?")){
		gapi.auth2.getAuthInstance().signOut();
	}
}

/******************** END AUTHENTICATION ********************/


/******************** PAGE LOAD ********************/
$(function(){
	$("#button-reload").click(function () {
        showLoading();
        showStatus("Loading Google Drive files...");
        getDriveFiles();
    });
	
	$("#button-upload").click(function () {
        $("#fUpload").click();
    });
	
	 $("#fUpload").bind("change", function () {
        var uploadObj = $("[id$=fUpload]");
        showLoading();
        showStatus("Uploading file in progress...");
        var file = uploadObj.prop("files")[0];
		var metadata = {
			'title': file.name,
			'description': "bytutorial.com File Upload",
			'mimeType': file.type || 'application/octet-stream',
			"parents": [{
				"kind": "drive#file",
				"id": FOLDER_ID
			}]
		};
		//if user upload an empty content, create a temp blob with a space content on it.
                if(file.size <= 0){
                       var emptyContent = " ";
                       file = new Blob([emptyContent], {type: file.type || 'application/octet-stream'});
                }
		showProgressPercentage(0);

		try{
			var uploader =new MediaUploader({
				file: file,
				token: gapi.auth.getToken().access_token,
				metadata: metadata,
				onError: function(response){
					var errorResponse = JSON.parse(response);
					showErrorMessage("Error: " + errorResponse.error.message);
					$("#fUpload").val("");
					$("#upload-percentage").hide(1000);
					getDriveFiles();
				},
				onComplete: function(response){
					hideStatus();
					$("#upload-percentage").hide(1000);
					var errorResponse = JSON.parse(response);
					if(errorResponse.message != null){
						showErrorMessage("Error: " + errorResponse.error.message);
						$("#fUpload").val("");
						getDriveFiles();
					}else{
						showStatus("Loading Google Drive files...");
						getDriveFiles();
					}
				},
				onProgress: function(event) {
					showProgressPercentage(Math.round(((event.loaded/event.total)*100), 0));
				},
				params: {
					convert:false,
					ocr: false
				}
			});
			uploader.upload();
		}catch(exc){
			showErrorMessage("Error: " + exc);
			$("#fUpload").val("");
			getDriveFiles();
		}
    });
	
	$("#button-share").click(function () {
        FOLDER_NAME = "";
        FOLDER_ID = "root";
        FOLDER_LEVEL = 0;
        FOLDER_ARRAY = [];
        $("#span-navigation").html("");
        $(this).toggleClass("flash");
		if($(this).attr("class").indexOf("flash") >= 0){
			$("#span-sharemode").html("ON");
		}else{
			$("#span-sharemode").html("OFF");
		}
        showLoading();
        showStatus("Loading Google Drive files...");
        getDriveFiles();
    });
	
	$("#button-addfolder").click(function () {
        $("#transparent-wrapper").show();
        $("#float-box").show();
        $("#txtFolder").val("");
    });
	
	$("#btnAddFolder").click(function () {
        if ($("#txtFolder").val() == "") {
            alert("Please enter the folder name");
        } else {
            $("#transparent-wrapper").hide();
            $("#float-box").hide();
            showLoading();
            showStatus("Creating folder in progress...");
			var access_token =  gapi.auth.getToken().access_token;
			var request = gapi.client.request({
			   'path': '/drive/v2/files/',
			   'method': 'POST',
			   'headers': {
				   'Content-Type': 'application/json',
				   'Authorization': 'Bearer ' + access_token,             
			   },
			   'body':{
				   "title" : $("#txtFolder").val(),
				   "mimeType" : "application/vnd.google-apps.folder",
				   "parents": [{
						"kind": "drive#file",
						"id": FOLDER_ID
					}]
			   }
			});

			request.execute(function(resp) { 
			   if (!resp.error) {
					showStatus("Loading Google Drive files...");
					getDriveFiles();
			   }else{
					hideStatus();
					hideLoading();
					showErrorMessage("Error: " + resp.error.message);
			   }
			});
        }
    });
	
	$(".btnClose, .imgClose").click(function () {
        $("#transparent-wrapper").hide();
        $(".float-box").hide();
    });
	
});

/******************** END PAGE LOAD ********************/

/******************** DRIVER API ********************/
function getDriveFiles(){
	showStatus("Loading Google Drive files...");
    gapi.client.load('drive', 'v2', getFiles);
}

function getFiles(){
	var query = "";
	if (ifShowSharedFiles()) {
		$(".button-opt").hide();
		query = (FOLDER_ID == "root") ? "trashed=false and sharedWithMe" : "trashed=false and '" + FOLDER_ID + "' in parents";
		if (FOLDER_ID != "root" && FOLDER_PERMISSION == "true") {
			$(".button-opt").show();
		}
	}else{
		$(".button-opt").show();
		query = "trashed=false and '" + FOLDER_ID + "' in parents";
	}
    var request = gapi.client.drive.files.list({
        'maxResults': NO_OF_FILES,
        'q': query
    });

    request.execute(function (resp) {
       if (!resp.error) {
			showUserInfo();
            DRIVE_FILES = resp.items;
            buildFiles();
       }else{
            showErrorMessage("Error: " + resp.error.message);
       }
    });
}

function showUserInfo(){
	var request = gapi.client.drive.about.get();
    var obj = {};
    request.execute(function(resp) { 
       if (!resp.error) {
			$("#drive-info").show();
			$("#span-name").html(resp.name);
			$("#span-totalQuota").html(formatBytes(resp.quotaBytesTotal));
			$("#span-usedQuota").html(formatBytes(resp.quotaBytesUsed));
       }else{
            showErrorMessage("Error: " + resp.error.message);
       }
   });
}

function buildFiles(){
	var fText = "";
    if (DRIVE_FILES.length > 0) {
        for (var i = 0; i < DRIVE_FILES.length; i++) {
			DRIVE_FILES[i].textContentURL = "";
			DRIVE_FILES[i].level = (parseInt(FOLDER_LEVEL) + 1).toString();
			DRIVE_FILES[i].parentID = (DRIVE_FILES[i].parents.length > 0) ? DRIVE_FILES[i].parents[0].id : "";
			DRIVE_FILES[i].thumbnailLink = DRIVE_FILES[i].thumbnailLink || '';
			DRIVE_FILES[i].fileType =  (DRIVE_FILES[i].fileExtension == null) ? "folder" : "file";
			DRIVE_FILES[i].permissionRole = DRIVE_FILES[i].userPermission.role;
			DRIVE_FILES[i].hasPermission = (DRIVE_FILES[i].permissionRole == "owner" || DRIVE_FILES[i].permissionRole == "writer");
			var textContentURL = '';
			if(DRIVE_FILES[i]['exportLinks'] != null){
				DRIVE_FILES[i].fileType = "file";
				DRIVE_FILES[i].textContentURL = DRIVE_FILES[i]['exportLinks']['text/plain'];
			}
			var textTitle = (DRIVE_FILES[i].fileType != "file") ? "Browse " + DRIVE_FILES[i].title : DRIVE_FILES[i].title;

            fText += "<div class='" + DRIVE_FILES[i].fileType + "-box'>";
			if (DRIVE_FILES[i].fileType != "file") {
				fText += "<div class='folder-icon' data-level='" + DRIVE_FILES[i].level + "' data-parent='" + DRIVE_FILES[i].parentID + "' data-size='" + DRIVE_FILES[i].fileSize + "' data-id='" + DRIVE_FILES[i].id + "' title='" + textTitle + "' data-name='" + DRIVE_FILES[i].title + "' data-has-permission='" +DRIVE_FILES[i].hasPermission + "'><div class='image-preview'><img src='images/folder.png'/></div></div>";
			} else {
				if (DRIVE_FILES[i].thumbnailLink) {
					fText += "<div class='image-icon'><div class='image-preview'><a href='" + DRIVE_FILES[i].thumbnailLink.replace("s220", "s800") + "' data-lightbox='image-" + i + "'><img src='" + DRIVE_FILES[i].thumbnailLink + "'/></a></div></div>";
				}else {
					fText += "<div class='file-icon'><div class='image-preview'><img src='images/" + DRIVE_FILES[i].fileExtension + "-icon.png" + "'/></div></div>";
				}
			}
			fText += "<div class='item-title'>" + DRIVE_FILES[i].title + "</div>";

			//button actions
			fText += "<div class='button-box'>";
				if (DRIVE_FILES[i].fileType != "folder") {
					fText += "<div class='button-download' title='Download' data-id='" + DRIVE_FILES[i].id + "' data-file-counter='" + i + "'></div>";
				}
				
				if (DRIVE_FILES[i].textContentURL != null && DRIVE_FILES[i].textContentURL.length > 0) {
					fText += "<div class='button-text' title='Get Text' data-id='" + DRIVE_FILES[i].id + "' data-file-counter='" + i + "'></div>";
				}
				
				fText += "<div class='button-info' title='Info' data-id='" + DRIVE_FILES[i].id + "' data-file-counter='" + i + "'></div>";
				
				if (DRIVE_FILES[i].hasPermission) {
					if (DRIVE_FILES[i].permissionRole == "owner") {
						fText += "<div class='button-delete' title='Delete' data-id='" + DRIVE_FILES[i].id + "'></div>";
					}else if(DRIVE_FILES[i].fileType != "folder"){
						fText += "<div class='button-delete' title='Delete' data-id='" + DRIVE_FILES[i].id + "'></div>";
					}
				}
				
			fText += "</div>";
			
			//closing div    
			fText += "</div>";
        }
    } else {
        fText = 'No files found.';
    }
    hideStatus();
    $("#drive-content").html(fText);
    initDriveButtons();
    hideLoading();
}

//Initialize the click button for each individual drive file/folder
//this need to be recalled everytime the Google Drive data is generated
function initDriveButtons(){
	//Initiate the delete button click
	$(".button-delete").unbind("click");
    $(".button-delete").click(function () {
        var c = confirm("Are you sure you want to delete this?");
        if (c) {
            showLoading();
            showStatus("Deleting file in progress...");
			var request = gapi.client.drive.files.delete({
				'fileId': $(this).attr("data-id")
			});

			request.execute(function(resp) { 
			   hideStatus();
			   if (resp.error) {
					showErrorMessage("Error: " + resp.error.message);
			   }
			   getDriveFiles();
			});
        }
    });
	
	//Initiate the download button
	$(".button-download").unbind("click");
    $(".button-download").click(function () {
        showLoading();
        showStatus("Downloading file in progress...");
        FILE_COUNTER = $(this).attr("data-file-counter");
        setTimeout(function () {
			//If there is a text version, we get this version instead.
			if(DRIVE_FILES[FILE_COUNTER].webContentLink == null){
				window.open(DRIVE_FILES[FILE_COUNTER]['exportLinks']['text/plain']);
			}else{
				window.open(DRIVE_FILES[FILE_COUNTER].webContentLink);
			}
			hideLoading();
			hideStatus();
		}, 1000);
    });
	
	$(".button-info").unbind("click");
    $(".button-info").click(function () {
		FILE_COUNTER = $(this).attr("data-file-counter");
        $("#transparent-wrapper").show();
        $("#float-box-info").show();
        if (DRIVE_FILES[FILE_COUNTER] != null) {
            var createdDate = new Date(DRIVE_FILES[FILE_COUNTER].createdDate);
            var modifiedDate = new Date(DRIVE_FILES[FILE_COUNTER].modifiedDate);
            $("#spanCreatedDate").html(createdDate.toString("dddd, d MMMM yyyy h:mm:ss tt"));
            $("#spanModifiedDate").html(modifiedDate.toString("dddd, d MMMM yyyy h:mm:ss tt"));
            $("#spanOwner").html((DRIVE_FILES[FILE_COUNTER].owners[0].displayName.length > 0) ? DRIVE_FILES[FILE_COUNTER].owners[0].displayName : "");
            $("#spanTitle").html(DRIVE_FILES[FILE_COUNTER].title);
            $("#spanSize").html((DRIVE_FILES[FILE_COUNTER].fileSize == null) ? "N/A" : formatBytes(DRIVE_FILES[FILE_COUNTER].fileSize));
            $("#spanExtension").html(DRIVE_FILES[FILE_COUNTER].fileExtension);
        }
    });
	
	//Initiate the get text button
	$(".button-text").unbind("click");
    $(".button-text").click(function () {
		FILE_COUNTER = $(this).attr("data-file-counter");
        showLoading();
		showStatus("Getting text file in progress...");
		var accessToken = gapi.auth.getToken().access_token;
		var xhr = new XMLHttpRequest();
		xhr.open('GET', DRIVE_FILES[FILE_COUNTER]['exportLinks']['text/plain']);
		xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
		xhr.onload = function() {
			callBackGetText(xhr.responseText);
		};
		xhr.onerror = function() {
			callBackGetText(null);
		};
		xhr.send();
    });
	
	//Initiate the click folder browse icon
	$(".folder-icon").unbind("click");
    $(".folder-icon").click(function () {
        browseFolder($(this));
    });

	//Initiate the breadcrumb navigation link click
    $("#drive-breadcrumb a").unbind("click");
    $("#drive-breadcrumb a").click(function () {
        browseFolder($(this));
    });
}


//browse folder
function browseFolder(obj) {
    FOLDER_ID = $(obj).attr("data-id");
    FOLDER_NAME = $(obj).attr("data-name");
    FOLDER_LEVEL = parseInt($(obj).attr("data-level"));
	FOLDER_PERMISSION = $(obj).attr("data-has-permission");

    if (typeof FOLDER_NAME === "undefined") {
        FOLDER_NAME = "";
        FOLDER_ID = "root";
        FOLDER_LEVEL = 0;
		FOLDER_PERMISSION = true;
        FOLDER_ARRAY = [];
    } else {
        if (FOLDER_LEVEL == FOLDER_ARRAY.length && FOLDER_LEVEL > 0) {
            //do nothing
        } else if (FOLDER_LEVEL < FOLDER_ARRAY.length) {
            var tmpArray = cloneObject(FOLDER_ARRAY);
            FOLDER_ARRAY = [];

            for (var i = 0; i < tmpArray.length; i++) {
                FOLDER_ARRAY.push(tmpArray[i]);
                if (tmpArray[i].Level >= FOLDER_LEVEL) { break; }
            }
        } else {
            var fd = {
                Name: FOLDER_NAME,
                ID: FOLDER_ID,
                Level: FOLDER_LEVEL,
				Permission: FOLDER_PERMISSION
            }
            FOLDER_ARRAY.push(fd);
        }
    }

    var sbNav = "";
    for (var i = 0; i < FOLDER_ARRAY.length; i++) {
        sbNav +="<span class='breadcrumb-arrow'></span>";
        sbNav +="<span class='folder-name'><a data-id='" + FOLDER_ARRAY[i].ID + "' data-level='" + FOLDER_ARRAY[i].Level + "' data-name='" + FOLDER_ARRAY[i].Name + "' data-has-permission='" + FOLDER_PERMISSION + "'>" + FOLDER_ARRAY[i].Name + "</a></span>";
    }
    $("#span-navigation").html(sbNav.toString());

    showLoading();
    showStatus("Loading Google Drive files...");
    getDriveFiles();
}

//call back function for getting text
function callBackGetText(response){
    if(response == null){
         showErrorMessage("Error getting text content.");
    }else{
        hideLoading();
        hideStatus();
        $("#transparent-wrapper").show();
        $("#float-box-text").show();
        $("#text-content").html(response.replace(/(\r\n|\n|\r)/gm, "<br>"));
    }
}

//function to clone an object
function cloneObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    var temp = obj.constructor(); 
    for (var key in obj) {
        temp[key] = cloneObject(obj[key]);
    }
    return temp;
}

//show whether the display mode is share files or not
function ifShowSharedFiles() {
    return ($("#button-share.flash").length > 0) ? true : false;
}

//function to return bytes into different string data format
function formatBytes(bytes) {
    if (bytes < 1024) return bytes + " Bytes";
    else if (bytes < 1048576) return (bytes / 1024).toFixed(3) + " KB";
    else if (bytes < 1073741824) return (bytes / 1048576).toFixed(3) + " MB";
    else return (bytes / 1073741824).toFixed(3) + " GB";
};

/******************** END DRIVER API ********************/



/******************** NOTIFICATION ********************/
//show loading animation
function showLoading() {
    if ($("#drive-box-loading").length === 0) {
        $("#drive-box").prepend("<div id='drive-box-loading'></div>");
    }
    $("#drive-box-loading").html("<div id='loading-wrapper'><div id='loading'><img src='images/loading-bubble.gif'></div></div>");
}

//hide loading animation
function hideLoading() {
    $("#drive-box-loading").html("");
}

//show status message
function showStatus(text) {
    $("#status-message").show();
    $("#status-message").html(text);
}

//hide status message
function hideStatus() {
    $("#status-message").hide();
    $("#status-message").html("");
}

//show upload progress
function showProgressPercentage(percentageValue) {
    if ($("#upload-percentage").length == 0) {
        $("#drive-box").prepend("<div id='upload-percentage' class='flash'></div>");
    }
    if (!$("#upload-percentage").is(":visible")) {
        $("#upload-percentage").show(1000);
    }
    $("#upload-percentage").html(percentageValue.toString() + "%");
}

//show error message
function showErrorMessage(errorMessage) {
    $("#error-message").html(errorMessage);
    $("#error-message").show(100);
    setTimeout(function () {
        $("#error-message").hide(100);
    }, 3000);
}

/******************** END NOTIFICATION ********************/

Understanding the JavaScript code.

Let's review the following code. In the first couple lines, we can see I have declared a list of global variables. Those global variables will be shared across the functions. There are two variables you need to review them carefully. The first one is the SCOPES. This identifies what type of permission you want to give the app to access your google drive. In this example, we give full permission where the app can perform mostly everything. The second variable is CLIENT_ID, this is a key generated when you create your new project app. Make sure when you create your new project, you enter the correct URL that is match with your site URL. If you want to do a testing URL, you can add more than one.

Please note: we do not actually need API_Key in here, as we want to get access permission from the user. So the Client ID is required. I have included the API Key in here for example only, you can remove it if needed. The API Key is basically used to access quota or non user related permission access.

Access SCOPES definition.

Please see the following table consist of available scopes.

Scope Description
https://www.googleapis.com/auth/drive Full permissive scope to access all of a user's files. Request this scope only when it is strictly necessary. Tokens with scope https://docs.google.com/feeds are accepted and treated the same as tokens with scope https://www.googleapis.com/auth/drive.
https://www.googleapis.com/auth/drive.readonly Allows read-only access to file metadata and file content
https://www.googleapis.com/auth/drive.appfolder Allows access to the Application Data folder
https://www.googleapis.com/auth/drive.apps.readonly Allows apps read-only access to the list of Drive apps a user has installed.
https://www.googleapis.com/auth/drive.file Per-file access to files created or opened by the app
https://www.googleapis.com/auth/drive.install Special scope used to let users approve installation of an app.
https://www.googleapis.com/auth/drive.metadata Allows read-write access to file metadata, but does not allow any access to read, download, write or upload file content. Does not support file creation, trashing or deletion. Also does not allow changing folders or sharing in order to prevent access escalation.
https://www.googleapis.com/auth/drive.metadata.readonly Allows read-only access to file metadata, but does not allow any access to read or download file content
https://www.googleapis.com/auth/drive.photos.readonly Allows read-only access to all photos. The spaces parameter must be set to photos.
https://www.googleapis.com/auth/drive.scripts Allows access to Apps Script files

How does the authentication work?

The authentication start working out when we load the following javascript file.

https://apis.google.com/js/client.js?onload=checkAuth

On the last line of the query string, you can see that after a complete load of the script, it will call a function named checkAuth. This checkAuth function will call google api function to start authenticating the user by specifying the scope and client id information. Once we get the result back, we can identify whether the user has already authenticated on the browser. If they haven't then we load the login box. The panel for login will have an id named login-box while for the drive files content will have an id of drive-box.

Most of the codes will have a comment heading on it, if you need further help, just drop your question in the comment form.


/******************** GLOBAL VARIABLES ********************/
var SCOPES = ['https://www.googleapis.com/auth/drive','profile'];
var CLIENT_ID = 'ENTER YOUR CLIENT ID HERE';
var FOLDER_NAME = "";
var FOLDER_ID = "root";
var FOLDER_PERMISSION = true;
var FOLDER_LEVEL = 0;
var NO_OF_FILES = 1000;
var DRIVE_FILES = [];
var FILE_COUNTER = 0;
var FOLDER_ARRAY = [];

/******************** AUTHENTICATION ********************/
function checkAuth() {
    gapi.auth.authorize({
        'client_id': CLIENT_ID,
        'scope': SCOPES.join(' '),
        'immediate': true
    }, handleAuthResult);
}

//authorize apps
function handleAuthClick(event) {
    gapi.auth.authorize(
          { client_id: CLIENT_ID, scope: SCOPES, immediate: false },
          handleAuthResult);
    return false;
}

//check the return authentication of the login is successful, we display the drive box and hide the login box.
function handleAuthResult(authResult) {
    if (authResult && !authResult.error) {
        $("#drive-box").css("display", "inline-block");
        $("#login-box").hide();
        $("#drive-box").removeClass("hide");
        showLoading();
        getDriveFiles();
    } else {
        $("#login-box").show();
        $("#drive-box").hide();
        $("#login-box").removeClass("hide");
    }
}
/******************** END AUTHENTICATION ********************/
<script src="https://apis.google.com/js/client.js?onload=checkAuth"></script>

This will be the css code, you can name this to google-drive.css.

body{
	font-family:arial;
	font-size:11px;
}


/*************** Google Login Box ***************/
#login-box{
	max-width:300px;
	border-radius:5px;
	border:solid 1px #ccc;
	padding:10px;
	background:#f0f9d7;
}
/*************** END Google Login Box ***************/

/*************** Google Drive Breadcrumb ***************/
#drive-breadcrumb{
	font-size:11px;
}

#drive-breadcrumb a{
	cursor:pointer;
}

.breadcrumb-arrow{
    background:url(images/arrow_right.png) no-repeat 0 3px;
    display:inline-block;
    height:16px;
    width:11px;
}
/*************** END Google Drive Breadcrumb ***************/

/*************** Google Drive Box ***************/
#transparent-wrapper
{
    display: none; 
    position: fixed;
    top: 0%; 
    left: 0%; 
    width: 100%; 
    height: 100%; 
    background-color: #000; 
    z-index: 1001;
    -moz-opacity: 0.35; 
    opacity: .35; 
    filter: alpha(opacity=35);
}

#drive-box{
    padding:10px;
    margin:10px;   
    border:solid 1px #ccc;
    width:98%;
    box-sizing: border-box;
    display:none;
    position:relative;
    min-height:150px;
    margin-top:60px;
}

#drive-content{
	clear:both;
}

.folder-box, .file-box {
    float:left;
    font-family:Arial;
    width:150px;
    height:150px;
    text-align:center;
    padding:10px;
    margin:10px;
    border:solid 1px #edeae9;
    -webkit-box-shadow: 7px 9px 5px -6px rgba(0,0,0,0.75);
    -moz-box-shadow: 7px 9px 5px -6px rgba(0,0,0,0.75);
    box-shadow: 7px 9px 5px -6px rgba(0,0,0,0.75);
	border-radius:5px;
}

.image-preview{
    text-align:center;
    height:80px; 
}

.image-preview img{
    max-width:45%;
	cursor:pointer;
}

.item-title {
    padding-top:10px;
    word-wrap: break-word;
    width:150px;
    text-align:center;
    font-size:11px;
    margin-bottom:10px;
}

#drive-menu{
    float:right;
    display:inline-block;
}

#drive-menu div:hover{
	background-color:#fafccc;
	border:solid 1px #000;
}

#button-reload, #button-share, #button-addfolder, #button-upload{
    width:24px;
    height:24px;
    display:block;
    cursor:pointer;
    margin-right:5px;
	float:left;
	border:Solid 1px #fae8e4;
	border-radius:5px;
}

#button-reload {
    background:url(images/button_reload.png) no-repeat;
}

#button-share {
    background:url(images/button_share.png) no-repeat;
}

#button-share.flash{
	background-color:#dbeb2d;
}

#button-addfolder {
    background:url(images/button_addfolder.png) no-repeat;
}

#button-upload {
    background:url(images/button_upload.png) no-repeat;
}

.button-box{
	padding-top:10px;
}

.button-delete, .button-info, .button-download, .button-text{
	width:20px;
    height:20px;
    display:inline-block;
    cursor:pointer;
    margin-right:5px;
}

.button-delete {
    background:url(images/button_delete.png) no-repeat;
}

.button-info {
    background:url(images/button_info.png) no-repeat;
}

.button-download {
    background:url(images/button_download.png) no-repeat;
}

.button-text {
    background:url(images/button_text.png) no-repeat;
}

/*************** END Google Drive Box ***************/

/************* User Drive Information **************/
#user-info
{
    position:absolute;
    height:100px;
    right:0;
    width:200px;
    margin-top:-110px;
    background:#338daf;
    z-index:99999999;
    color:#fff;
    padding:5px;
    box-sizing: border-box;
    text-align:right;
    font-size:11px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

.user-item
{
    padding-bottom:4px;
}

#drive-info{
	position:absolute;
    height:90px;
    right:0;
    width:200px;
    margin-top:-120px;
    background:#338daf;
    z-index:99999999;
    color:#fff;
    padding:5px;
    box-sizing: border-box;
    text-align:right;
    font-size:11px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}
/************* END User Drive Information **************/

/************* FLOATING BOX *********************/
.float-box{
    border-radius:0px;
    -webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
    -moz-box-shadow:7px 7px 5px rgba(50, 50, 50, 0.75);
    box-shadow:7px 7px 5px rgba(50, 50, 50, 0.75);
    width:400px;
    padding:7px 15px;
    border:solid 1px #ccc;
    position:fixed;
    left:50%;
    margin-left:-200px;
    top:35%;
    z-index:1000000;
    background-color:#fff;
    display:none;
}

.close-x{
    float:right;
    display:inline-block;
	cursor:pointer;
}

.tbl-info{
    border-left:solid 1px #ccc;
    border-top:solid 1px #ccc;
    margin-bottom:10px;
    width:100%;
}

.tbl-info td{
    border-right:solid 1px #ccc;
    border-bottom:solid 1px #ccc;
    padding:5px 10px;
	font-size:11px;
}

.tbl-info td.label{
    background:#5f5d5c;
    color:#fff;
    text-align:right;
    width:50%;
}

#text-content
{
    margin-bottom:10px;
    overflow-y:auto;
    overflow-x:hidden;
    height:180px;
	border:solid 1px #ccc;
}

.text-input{
    width:90%;
    padding:5px;
    border-radius:5px;
    margin-bottom:10px;
}
/************* END FLOATING BOX *********************/

/*************** NOTIFICATION ******************/
#loading-wrapper{
    width:100%;
    height:100%;
    background:#000;
    -moz-opacity: 0.25; 
    opacity: .25; 
    filter: alpha(opacity=25);
    top:0;
    left:0;
    position:absolute;
}

#loading{
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-60px;
    margin-top:-60px;
    width:120px;
}

#status-message{
    border:solid 1px #fbfbd4;
    background:#fbfbd4;
    border-radius:5px;
    padding:5px;
    position:absolute;
    right:10px;
    bottom:10px;
    z-index:9999999999;
}

#error-message{
    border:solid 1px #f2fcb9;
    background:#d83813;
    border-radius:5px;
    color:#fff;
    padding:10px;
    position:absolute;
    left:10px;
    bottom:10px;
    z-index:9999999999;
    max-width:400px;
    border-radius:5px;
    display:none;
}

#upload-percentage{
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-25px;
    margin-top:-100px;
    width:50px;
    height:50px;
    border-radius: 50%;
    background:#297ab8;
    color:#fff;
    text-align:center;
    line-height:50px;
    font-weight:bold;
    font-size:15px;
    display:none;
}
/*************** END NOTIFICATION ******************/

/***************** MISC ************************/
.button {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  border:none;
  -webkit-border-radius: 8;
  -moz-border-radius: 8;
  border-radius: 8px;
  font-family: Arial;
  color: #ffffff;
  font-size: 11px;
  padding: 5px 10px;
  text-decoration: none;
  cursor:pointer;
}

.button:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
  border:none;
}

.hide{
	display:none;
}

.flash {
    -webkit-animation-name: flash;
    -webkit-animation-duration: 1s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;

    -moz-animation-name: flash;
    -moz-animation-duration: 1s;
    -moz-animation-timing-function: linear;
    -moz-animation-iteration-count: infinite;

    animation-name: flash;
    animation-duration: 1s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

@-moz-keyframes flash {  
    0% { opacity: 1.0; }
    50% { opacity: 0.5; }
    100% { opacity: 1.0; }
}

@-webkit-keyframes flash {  
    0% { opacity: 1.0; }
    50% { opacity: 0.5; }
    100% { opacity: 1.0; }
}

@keyframes flash {  
    0% { opacity: 1.0; }
    50% { opacity: 0.5; }
    100% { opacity: 1.0; }
}

/***************** END MISC ************************/

Google API Drive demo files

Please click here to download the demo file.

Download

Please note in order for the download files to run correctly on your computer, you will need to replace the API key and set the url of the google apps correctly. See above information for more details.

If you have any question, feel free to leave your comment below.

Comments

netdev
07 Mar, 2016
how can we implement abort option for current upload file.? please suggest. may be a button on ui when click current upload can be aborted?
andy
07 Mar, 2016
Unfortunately, I couldn't find any documentation in API JavaScript to abort the ongoing upload. If you do find the solution, please share with us.
Hao
21 Mar, 2016
How can I run this app? I have download the zip file.
andy
21 Mar, 2016
Firstly you will need to create your own API Key, and replace it with the current key available in the example file. Once you have done it, you should be able to run. Just make sure the url address you open the apps is the same on your API apps url.
Jen
13 Oct, 2022
Is this still functional now?
hui
08 Mar, 2016
how to change the default folder?
andy
08 Mar, 2016
In the google-drive.js file, there is a global variable called FOLDER_ID, by default the value is set to 'root', this is the default root of your google drive folder, simply change this to the ID of specific folder you want to use.
hui
08 Mar, 2016
but how to identify the ID of my folder?
andy
09 Mar, 2016
Hi Hui, Please look for word function buildFiles(){} the file or folder id is identified by this code: DRIVE_FILES[i].id Just use console.log(DRIVE_FILES[i].id) to see what is the folder id. Let me know if you need further help
Akash soni
05 Apr, 2016
how to share files and folders on google drive in javascript? please give me a demo.
andy
05 Apr, 2016
Hi Akash, Please follow the above tutorial. You need to create your own API key and replace the api key on the sample code. Make sure you add the correct url address. If you are working on a local computer or usually localhost. You then add localhost as your url address. Hope this makes sense.
Ayush
28 Sep, 2016
where to add the url address?
andy
28 Sep, 2016
When you create your google API in google console, you will be asked to enter the url of your apps.
Dhananjay
19 May, 2016
please tell me how to validate my own account and how to get login success response from google authentication login. i need to check logged user should be my own account.
andy
20 Jun, 2016
Hi Dhananjay, In order to get the validation work properly, please make sure your working url is exactly the same you add in your google drive apps. Otherwise you will get an error. What I could suggest, is to do it step by step by reading the article again. Or just download the demo files and see it how it works.
Vlad
26 May, 2016
Hello, I have setup your demo and it's working great, except for uploading certain types of files. I can upload .jpg and .png image files with no problem. However, when I try to upload some other file types, I get the following error: 1) Example #1 - Uploading .txt file gives this error: Error: OCR is not supported for files of type text/plain. 2) Example #2 - When I try to upload a .exe file, the error becomes: Error: OCR is not supported for files of type application/x-msdownload. Is it possible to enable the upload of ALL file types (.doc, .docx, .txt, ect)? Thank you!
andy
20 Jun, 2016
Hi Vlad, On the javascript looks for the following variable and set it to false. ocr: true
Liza
07 Jun, 2016
Hi I am using localhost and I m not able to upload .ppt files or .txt files to the drive.Only images are getting added. Please suggest
andy
20 Jun, 2016
Hi Liza, Just disable the ocr: false. Look for the wording OCR in the javascript file.
Devendra
07 Jun, 2016
Thanks Andy for this wonderful package. You reduced my effort :)
Phu
17 Jun, 2016
Hi, I have trouble downloading files using javascript API. var request = gapi.client.drive.files.get({ fileId:id, alt:'media' }); request.execute(function(resp){ console.log(resp); }); this returns 403 or 400 errors depends on the type of files (binary or non-binary) var request = gapi.client.drive.files.get({ fileId:element.id, }); request.then(function(resp){ console.log(resp.result); type = resp.result.mimeType; id = resp.result.id; var request = gapi.client.drive.files.export({ fileId:id, mimeType:type }) request.execute(function(resp){ console.log(resp); }); }); This returns 403 error with insuffiecient permission for all files.
andy
20 Jun, 2016
Hi Phu, make sure the scope of your apps permission is set to full permission otherwise you will get this error.
sorav garg
25 Jun, 2016
Hello, awesome code did it with in few minutes, great post, i like it only i have single issue when i load page first it`s load whole data of google drive into my site so it`s taking too much time of i have large data on my drive can we bypass this or do you have any alternate way to ignore this because user can`t wait for long time, please reply me asap. Thanks
andy
06 Jul, 2016
Hi Sorav, Sorry for the late reply. You may want to reference this API documentation. https://developers.google.com/drive/v2/reference/files/list#parameters by default the maxResults is not specify if you set this value to a number you want, it should solve the loading problem. Alternatively, you want to use query q keyword to help sorting the number of files.
Mare Verde
01 Jul, 2016
To try the quickdemo you say: If you want to try the demo, you can simply login on the google site and link your account to this app. I am newbie to google apps. Can you please be more specific?
andy
06 Jul, 2016
Please just ignore this, I have removed the content to avoid confusion. Just use the demo file instead.
Martin
11 Jul, 2016
Hi, after i change client id and login, in console say that on 295 line have error (Uncaught TypeError: Cannot read property 'length' of undefined) if (DRIVE_FILES[i].textContentURL.length> 0) { fText += "
"; } I try to fix it but....
andy
13 Jul, 2016
Hi Martin, could you please check if you do not accidentally remove any extra code line? Or have you set the permission correctly?
robin
18 Jul, 2016
I am getting the same error
andy
21 Jul, 2016
Hi Robin, Please see the following quick demo example. Just view the js source code and copy it if require and compare the code using notepad++ and see what are the differences. http://bytutorial.com/Assets/content/files/googledrive/google-drive.html
Pablo
25 Nov, 2016
Hi Andy, i'm getting the same error of them... with downloaded files and the demo link you posted before: google-drive.js:294 Uncaught TypeError: Cannot read property 'length' of undefined(…) i just commented lines 294 and 296 and it worked for me...
andy
28 Nov, 2016
Hi Pablo, It seems to me that the textContentURL is null, i just modify the code to include this to make sure it doesnt return error. DRIVE_FILES[i].textContentURL != null
Ahilan
13 Jul, 2016
It does not seem to be working for Google native docs such as Google Sheets, Google Drawings etc. It seems to go in infinite loop for such docs. Any suggestions?
Anmol Maini
20 Jul, 2016
Hey andy, Is there any way I can sign into a particular user's account on the client side, without their interaction
andy
21 Jul, 2016
Hi Anmol, Unfortunately you will need user interaction in order to get a list of their files.
Rajiv
22 Jul, 2016
Hi Andy, I get the following error Cannot read property 'length' of undefined When I wrote DRIVE_FILES[i]['exportLinks']['text/plain'] shows undefined in "console.log" it showed "undefined". Please let me know what I have missed. Looking forward for your reply.
ilias naamane
06 Aug, 2016
Hello I have downloaded the zip file , and after that I have put the right client _id , and right url in my configuration anyway please , I have got two errors after login :1) The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. google-drive.html TypeError: DRIVE_FILES[i].textContentURL is undefined . Thanks .
andy
12 Aug, 2016
Hi Ilias, Possible to put it on a live url so I can actually see what is wrong?
Emmanuel
16 Aug, 2016
Just wanted to thank you for this tutorial which has saved me lots of time. Thanks again for sharing.
Samuel
03 Sep, 2016
Hi Andy, Thanks for tutorial, it's work fine to me. How create fetch url for streaming video in gdrive? any link for tutorial? like redirector.google generate thanks befor.
andy
06 Sep, 2016
I actually never upload any videos into my account. however, when you perform a loop on your google drive files, it should return you a url link if it is applicable. Try copy this url and paste it into the browser and see if it works. Make sure the link is visible for public.
votuong
04 Sep, 2016
Thank the code, but i need user offline. please
andy
06 Sep, 2016
Unfortunately the sample code given require an online connection. You may want to see the example given on google site by writing it on console windows application example.
Vo Tuong
06 Sep, 2016
You misunderstood yourself then. I want to use my token and consumers can use to upload files to my drive, not the drive's account of consumers.
andy
06 Sep, 2016
Hi Vo, Try have a look on this article? http://lifehacker.com/allow-others-to-upload-files-to-your-google-drive-with-1567528648
Arjun
08 Oct, 2016
Nice article . I am try to do OCR also . I do get response in json format . the key is external links. when i hit that url it start downloading I want to show the text in text box instead of downloading the file.
andy
12 Oct, 2016
Just search for the OCR option in the code and set it to true, i think i set it into false as in the code.
Soruc
12 Oct, 2016
Hey i have a question Is this possible http://stackoverflow.com/questions/39976654/link-a-link-to-google-drive-api-folder ? Things u showed here ( man god bless u) i have searched for weeks
soruc
17 Oct, 2016
How can i when i delete something that it goes to trash and it won't be showed ??? so that the owner can restore it. ? because deleting it permanently is risky for me.
andy
18 Oct, 2016
Hi Soruc, as far as I know, it should place it into the trash folder. It doesnt delete them permanently. Just wonder have you tested and it didnt go to trash folder?
keesje
18 Oct, 2016
change the line in function initDrivebuttons() to var request = gapi.client.drive.files.trash
Selim
19 Oct, 2016
After i tested i needed to be sure if it deleted permanently or trash it skips the trash. https://developers.google.com/drive/v3/reference/files/delete "Permanently deletes a file owned by the user without moving it to the trash. If the target is a folder, all descendants owned by the user are also deleted. Try it now."
andy
25 Oct, 2016
Hi Selim, just follow the advice made by Keesje. Just add the trash keyword in this line: var request = gapi.client.drive.files.trash in javascript. For more info on this please refer to this page. https://developers.google.com/drive/v2/reference/files/delete
andy
25 Oct, 2016
Thanks Keesje ;-)
Keesje
24 Oct, 2016
I have same question as Vlad. Where do i have to put the types of the files i want to upload.??? I want to upload powerpoint(.pptx) what do i have to change or where do i have to add the code to make sure this can be uploaded ?? And if i have more types how do i add it ????
andy
25 Oct, 2016
In the javascript code, try set the 'mimeType': '*/*'. This is specified by the document reference in google api. https://developers.google.com/drive/v2/reference/files/insert Btw, there are images folder to display file extension, so you may want to create and place the image into that folder otherwise it will display the default image file.
keesje
25 Oct, 2016
i have changed 'mimeType': file.type || 'application/octet-stream' , this into 'mimeType': file.type || 'application/octet-stream' || 'application/vnd.openxmlformats-officedocument.presentationml.presentation', but it still doesnt work ??? how do i have to do it ? can u help me with this ? http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc
andy
26 Oct, 2016
Actually i just place back the demo link. it works fine for me, when i tried to put a sample pptx file. Try upload the file using the demo link i put it on the site at the end of the article.
Keesje
27 Oct, 2016
I have tried from ur demo link and when i try to add an pptx i got the error : Failed to load resource: the server responded with a status of 400 ()
andy
28 Oct, 2016
Hi Keesje, Is it possible that you can use web tools or fiddler to get the error message when you upload the file? How big is the file? Or is there a way that you can create a dummy google mail account and send me the login details? I will upload some test pptx file.
MrSik
25 Oct, 2016
How can I use drag drop (for upload) And select and upload more than 1 file at the time ??? I have found a script (dropzone.js) the only thing is I can't implement it to the script u using here. Can u help me with this problem.
andy
26 Oct, 2016
Sorry that I never use it before. But the logic on how to use it should be the same like the Jquery drag and drop. For the multi file upload, you may be able to place the files into an array and upload the remaining files once the previous file is completed. See the sample of multiple uploads with queue method i use on this example. http://bytutorial.com/blogs/aspnet/upload-multiple-files-using-jquery-and-generic-handler
MrSik
31 Oct, 2016
how can i implement this code into ur code above ??? (srry but i am kind of new with this)
WeiHsiung
04 Nov, 2016
I've downloaded the zip file, unziped them, and uploaded them to a web server. In addition, I've completed step 1 and put the client id in the google-drive.js. Could you tell me how to run this? When I open google-drive.html on the web server, I see the following message.. "A quick example of utilizing Google Drive API using javascript and JQuery library. You will learn almost all of the basic of the Google Drive features in 60 minutes. I will include the step by step explanation and features that will be included on this tutorial. How to create your first Google Drive apps. Layout a login panel and google drive directories and files. Features like creating and deleting folder, upload and delete, browse folder, show shared folders and files, show upload progress, preview images in lightbox, convert uploaded file to google doc or OCR readable, show the user information and add the logout link." (there are more, I only pasted part of them...)
andy
10 Nov, 2016
Hi WeiHsiung, i have removed all the text from the sample demo. So it will now only include the demo text only. Exactly the same with the sample demo page. Would you like to try use this version?
Dave
22 Nov, 2016
Is it possible to show files that I shared with the gmail account that uses this code ??? if I click on the show shared files I can see files that has been shared with me. Is it possible to see files that I shared ?
andy
28 Nov, 2016
Hi Dave, Unfortunately there is no option in the search parameters. However you may able to include the owners in the query parameter. See this parameters API: https://developers.google.com/drive/v3/web/search-parameters?hl=en In my example, I am using keyword sharedWithMe, you may give it a try to use owners instead.
dave
25 Nov, 2016
I try to use multiple uploads at once. But failed. Can you help me how to do it. I looked into the link you shared with the same question as this but didnt come far. :(
Anton Hilman
14 Dec, 2016
hi andy thanks for your tutorial. how about anonymous can upload file to my google drive.
andy
06 Feb, 2017
Sorry for the late reply, Unfortunately anonymous is not supported.
BulBul
27 Dec, 2016
Hey Andy, First of all thnx for this great piece of work. I have 1 question. I Have the same question as MrSik. I try to implement drag and drop but failed. Is there a easy way ? (i am a beginner at this) the problem with the code that i found is to connect to google drive api en let it work with youre code . Can u help me with this problem ?
Abhijit Roy
11 Jan, 2017
how to share files and folders on google drive in javascript?
Abhishek Sharma
30 Jan, 2017
Really thanx for this and thanx for your efforts for this it works like charm :)
Coisox
10 Feb, 2017
By providing my CLIENT_ID, I must login with the same account I do the configuration on developer console. The data will be save into my GDrive. How to make it save into any logged in user's account? Are we still using the same API? I got confuse with Google Drive SDK
andy
13 Feb, 2017
Hi Coisox, You still use the same API, just consider this as your developer API, so everyone want to access their google drive can use your API details. You can test this by creating a new gmail account and try it.
Shahan Syed
19 Mar, 2017
You are amazing for putting this together for the community ! You are what keeps our dev community thriving !
awanet
23 Mar, 2017
Hello, great job. when i tried you demo link it is superb but when i downloaded the demo file it only showing blank page and i had my CLIENT ID inserted also at google drive api i had my url = http://localhost:54007. therefore onmy browser i type http://localhost:54007/google-api-drive-bytutorial.com/google-drive.html. pls,let me also enjoy your workas others.
awanet
23 Mar, 2017
HI andy, i have made it work the problem is from URL Thanks.
andy
29 Mar, 2017
Glad you get it works ;-)
Yashesh
01 Apr, 2017
Hey :) thank you for this Beautiful effort... a small question.. what if I want to share the files on the drive (Change Permissions and get links) is it possible.. it'd be very kind if you could tell me how :)
andy
03 Apr, 2017
Hi Yashesh There is a share button available in the demo to show only share files. You can get the path of the link share file, but users still need to login in order to get the link working. What i mean users in here are persons that you share the files with.
noman
01 Apr, 2017
HI andy How r u? i came across Your Blog during searching Of Google drive Video in Jw player, I was looking the code on internet but Nothing found May be your Code works Actually I wanted to player Video File of google Drive in Jw player many of the people Providing api for but i want to make my own like this one embedto .com do u have some help for me ?
andy
03 Apr, 2017
Hi Noman, I am not quite sure if it can be done, try copy the jw player scripts in the same folder where your google drives are hosted and paste the link of the file into your JW code and see if it can be played.
Michael joyner
08 Apr, 2017
Andy, have you worked with the V3 api? Can you please contact me michaelwjoyner_at_gmail.com We are a integrations company and we are extending into Google Drive.
Michael Joyner
08 Apr, 2017
Andy, I was getting this error when I ran in Chrome. Refused to display 'https://accounts.google.com/o/oauth2/auth?client_id=954144990383-p3h69sqt01…res__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCOhsv9xX_WBHU8Tw401kRqG7k3UMQ' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
andy
10 Apr, 2017
Hi Michael, I havent worked on version 3 yet. I look into the quick documentation, seems to be pretty similar. Regarding with the chrome message issue. Did you get this when you try to load my demo page on this site?
Michael joyner
10 Apr, 2017
I was running the example from my IDE localhost:6432 and i went back into google console and updated uri_redirect with localhost:6432 and the SAMEORGIN error went away. We have developed a product for Dropbox that we are porting to Google Drive and I would like to know if your situation could allow professional help. We have a knowledgeable staff I would just feel more comfortable if we had someone that we could consult with if we got stuck. Let me know, you have my email address.
Samir
26 Apr, 2017
Hello Andy, Thanks for your tutorial. I got this error message when I tried to run the application: "Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').". Can I know why I got this error message ? Thanks.
Khushi
15 May, 2020
Can you please tell me. How you did solve this problem.
Samir
26 Apr, 2017
Hello Andy, I did fix the issue I was facing. Thanks.
andy
26 Apr, 2017
Ok that is great. Usually this issue came when your api url address is not match with the current url address you test.
Miles
17 May, 2017
Is it possible to download a whole folder ? with files and subfolders in it ?
andy
19 May, 2017
Hi Miles, Not as far as i know. Even in the google drive itself, you cant download the whole folder.
asma
07 Jun, 2017
Hi Andy, I was getting this error when I ran in Chrome and firefox. Refused to display 'https://accounts.google.com/o/oauth2/auth?client_id=569261979352-tt3p76hcka…res__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCP6qL6fKxM6ls2ZRo09HfLKjh2bZQ' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
asma
07 Jun, 2017
Hello Andy, i get this error 401. That’s an error. Error: invalid_client no registered origin Request Details client_id=555170076757-d5fot4jh90dkrtj81it6ahpvbu4st6vv.apps.googleusercontent.com scope=https://www.googleapis.com/auth/drive profile immediate=false include_granted_scopes=true proxy=oauth2relay1328717968 redirect_uri=postmessage origin=http://localhost response_type=token gsiwebsdk=1 state=1255778469|0.2635885199 jsh=m;/_/scs/apps-static/_/js/k=oz.gapi.en.mA1GnGpfQiI.O/m=__features__/am=AQ/rt=j/d=1/rs=AGLTcCP6qL6fKxM6ls2ZRo09HfLKjh2bZQ That’s all we know. please i need your help
andy
28 Jul, 2017
Hi Asma, In the HTTP Referrers, make sure you enter the correct url path. if you are working on http://localhost, then enter the address there. I have now included the image on above article.
dani
18 Jun, 2017
how i can download from url
Angela
23 Jun, 2017
First thanks so much for posting an example of usage with google drive. This maybe a stupid question but I was searching for docs that would explain this "gapi.client.drive.files.list" (example in your code when I came across your code. in other words how did you find out what the structure was that came after "gapi.client"? Like you have ".drive.files.list" I am looking at this https://developers.google.com/drive/v2/web/about-sdk And I know there is a reference for the API which spells out the structure. But how did you know to put ".drive" in there? I have seen other examples for people that do "people.people"... Trying to figure out the structure of the javascript client and if there is actually any documentation to it that tells how to access the various APIs. Thanks again for the help :) Angela
andy
28 Jul, 2017
Hi Angela, Sorry for the late reply, it is actually came from the google SDK. See this link under the File:List specs https://developers.google.com/drive/v2/reference/files/list
sairam
24 Jul, 2017
IT'S NOT WORKING WHEN OPEN HTML PAGE IT'S BLANK PAGE DISPLAYING
andy
27 Jul, 2017
Hi Sairam, I can confirm that the demo page still work fine. I just tested the page now. http://bytutorial.com/assets/content/files/googledrive/google-drive.html
manu
08 Sep, 2017
You are using oauth1. I thought google deprecated oauth1 and moved onto oauth2. But oauth1 still works here.. Not sure whats happening. What all difference do i have to make to port it into oauth2.
andy
06 Oct, 2017
Hi Manu, It is actually use oauth2, if you see the actual source script from javascript. I have modified the code to use the following example, so it doesnt confuse you. https://developers.google.com/identity/protocols/OAuth2UserAgent
Alexei
11 Nov, 2017
Hey, I know that it's an old post, but i'm desperate to find a solution for mu problem. As far as I can see, you are familiar with drive api. May be you could help me with this. i didnt find this in docs. is there any restrictions for non logged user to view the content? I have public folder (view only) and trying to get folders content. problem is that im able to get content using only one ID. if i try to get more than one ID, getting an error "The user does not have sufficient permissions for this file." if i'm logging in with any account which is added ad viewer for this folder it works well. here is an example of my code: (next comment)
Alexei
11 Nov, 2017
gapi.load('client', function(){ gapi.client.load('drive', 'v3', function(){ gapi.client.init({ clientId: '1051020924675-59qgl58th06ft9s160cnp28j7a3uunte.apps.googleusercontent.com', discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'], scope: 'https://www.googleapis.com/auth/drive.readonly', apiKey: 'AIzaSyDDkKdDATJQLaIkn47lUe2khAHOQ2SslUE' } ).then(function(){ gapi.client.drive.files.list({ 'q' : "('0B3vR4cBcxn4odWprdmc5emRoYU0' in parents or '0B3vR4cBcxn4oLW5COHlyQXF6VEU' in parents)", 'pageSize' : 10, 'fields' : "nextPageToken, files(id, name, webContentLink, folderColorRgb, thumbnailLink, description)", 'orderBy' : 'modifiedTime desc', }).then(function(respo){console.log(respo)})
andy
14 Nov, 2017
Hi Alexei, based on the error you have, it looks like you do not have the access to folder. Could you try to change the scope in your scope to this and see if it works fine. ['https://www.googleapis.com/auth/drive','profile']; If it does, try check again the permission on the folder itself.
Sameer
07 Dec, 2017
Hi, I am getting below error while uploading any file on drive cannot read property 'access_token' of null
andy
18 Dec, 2017
Have you setup your Google API Key correctly? Try this, copy the download example file and replace with your own key. But make sure you set the scope permission correctly and try run the page and see if it works.
Sameeer
19 Dec, 2017
Yes it was set correctly.but don't know how it getting this error
andy
19 Dec, 2017
Have you set it up available in a website url? so I can have a look? Have you tried the recommendation i said before where you just copy the demo file provided and replace the API key with your own?
dimas
02 Jan, 2018
When i try Upload Error: TypeError: gapi.auth.getToken(...) is null plis help?
andy
06 Jan, 2018
Hi Dimas, I have fixed the problem, there is a bit of issue on getting the access token when using oauth 2. You can try the demo or download the latest files. If you try the demo version, make sure you refresh your browser so it get the latest google drive javascript file (not cached old version).
Janter Alexander
02 Jan, 2018
1. blank page going from sub dir how to use this script in a sub folder ?
andy
06 Jan, 2018
Hi Janter, there is a bit of issue on getting the access token when using oauth 2. I have updated the code. Please try the demo version and create a sub folder and it should be ok now. If you try the demo version, make sure you refresh your browser so it get the latest google drive javascript file (not cached old version).
Janter Alexander
02 Jan, 2018
2. and im stuck at Loading Google Drive files...
gsboris
06 Jan, 2018
Problem: 1st I get the message that app is not registered, but it goes through and them Loading Google Drive Files forever.
andy
06 Jan, 2018
Hi gsboris, would you like to try again by refreshing the site? Make sure the script is not cached as I just updated the file. I do get a notification from Google about the unverified app. I am submitting a review to Google to notify them about this app is for a tutorial purpose only.
gsboris
10 Jan, 2018
Great, it works perfectly now. Thanks.
nit kumar
25 Jan, 2018
First of all thanks sir for this project Please implement thi project little bit i have few ideas but i don't know javascript. 1) move files & folders to another location ( Priority - medium) 2) Please add an option to login with another account without loging out present account( high) Thing what i love about this project is 1)It is awesome for mobile devices. 2) If you delete file by this script you don't need to delete this from trash.
Janica
30 Jan, 2018
Hi! really nice tutorial, had no trouble at all implementing it and getting it to work, as opposed to other examples that you can find online. Tell me something, is there a way to change the way the credentials are stored, in order to be server-side like php, instead of js? It causes me some awkwardness having the client-id available in any debugger console.. thank you for this share!
andy
30 Jan, 2018
Hi Janica, What you can do is empty the credential information in the javascript code. In the function handleClientLoad, perform a JSON request to your server to get the credential and once the credential has been retrieved then perform this call function gapi.load('client:auth2', initClient). You can include another function that can perform decrypt or encrypt if needed. Note: Even your credential is visible in the code, nobody still can use it as Google has included a javascript origin source to prevent this, so I don't think it is necessary to do this.
gary goodridge
06 Feb, 2018
Hello, the code works. However, I would like to display several folders at the same time, please. thank you
andy
07 Feb, 2018
Hi Gary, Not quite sure what you mean by display several folders at the same time. Basically, the way how it works will be exactly like viewing a windows explorer. The folders and files will be listed first in the root folder. If you have more than one folder, it will still be displayed.
Stuti
13 Feb, 2018
Hi Andy, Thanks for your tutorial, it really works! i want few changes to be done and can you please explain and guide me on how to go about the same. I would be sharing a link with say 10 people, and i want all of them to upload their files onto one specific shared folder ( to my original drive ) from their account. Is this possible? How to proceed, and what are the changes i need to do to the Google API?
andy
13 Feb, 2018
Hi Stuti, I believe in the example I gave in the tutorial demo already include a button to show shared files/folders already. What you need to do basically is to create a folder and then share the folder by sending the link to all users' emails so they can upload the folder link you sent. Once they upload, you can click the share folder icon and it should show all the files uploaded there.
Stuti
16 Feb, 2018
Thanks for your prompt reply Andy, yes that share button is useful. But how do i share the uploaded files to the users' emails? Can you please let me know where i need to provide this access? Anything i need to modify in the function insertPermission()? Please let me know, and thanks once again!
andy
19 Feb, 2018
Hi Stuti, I haven't got that far. You may have to check Google API on how to share programmatically via code.
ken kaneki
03 Mar, 2018
How to upload from direct link ?
andy
04 Mar, 2018
Could you please advise what do you mean by direct link?
mederick
09 Mar, 2018
hello ,First thanks for this tutorial. I want to play video please.
andy
10 Mar, 2018
You should be able to play it directly in the browser if you view the link. I double check this by see someone posting the shared video link. For example: https://drive.google.com/file/d/0B25Xsf1r3lGjM0pnT2lSTHljUEE/view You can then create your own video wrapper using HTML5. Please see my other tutorial about Video control in HTML5
corleone
13 Mar, 2018
Hello , I'd like to thank you for your tutorial, it helped me a lot. I'm having some issues. I'm developing a web app using Google drive account to show its media files . When I enter the app even though I connected it to the drive to get the files. It keeps asking Google ID and password in order to enter my app. But it doesn't matter which account I'm using in the Google connection pop-up, it still working. So I'd like to bypass the authentification pop-up or in other words to skip this step. Thank you for your help
andy
13 Mar, 2018
Try to check the permission you specify in the google app. You cant bypass the pop up authentication. As long as it requires you to log in. It will always pop up.
donKing
30 May, 2018
Hello thank you . How can load files on scroll please . (ajax?) thank you for your help
gervj
30 May, 2018
Hi andy, Came across your tutorial searching for way to display specific gdrive folder as a photogallery webpage (like divegal,lghtbx, sprout.photo all not working ) As a total noob the tutorial was much helpful. Is it possible to login once and then the link permanently display the drive folder instead of taking to login page each time so that the link can be shared publicly?
andy
31 May, 2018
Hi Gervj, Unfortunately, login is always required when using the website app. When you create a google app you might be able to use their api key for console or mobile app that does not require login. Note: login is always required for accessing any requested other person drives.
Govind
01 Jun, 2018
Hi andy, When i m trying to upload a text file of 0 KB to my google drive . I m getting an 404 error. Request headers have below data. content-length: 0 content-range: bytes 0--1/0 any suggestion, how to fix this issue and allow uploading of 0KB file uploading ?
andy
03 Jun, 2018
Hi Govind, yeah, I can see the issue with the 0kb upload. I couldn't figure it out how it has been rejected. If someone has a solution please share in here. Meanwhile, you may be able to add a temporary warning not to allow users to upload 0kb file.
andy
06 Jun, 2018
Hi Govind, Just let you know I have fixed this issue. I have come with a quick solution to set a temp blob empty content with a space. In the upload bind event. I have included the following condition.
//if user upload an empty content, create a temp blob with a space content on it.
if(file.size <= 0){
     var emptyContent = " ";
     file = new Blob([emptyContent], {type: file.type || 'application/octet-stream'});
}
It will use the uploaded properties file. The only thing different has I added an extra space automatically in the content.
Lokesh
22 Jun, 2018
Hi Andy, Thank you for your tutorial. I have a problem with this. The code is running properly in python webserver, but it is giving problem with xampp webserver.This is the error showing while executing. //--- Not a valid origin for the client: http://localhost has not been whitelisted for client ID. Please go to https://console.developers.google.com/ and whitelist this origin for your project's client ID."--- // I even added the xampp localhost url in the credentials and whitelisted but still the same error. Please do help me out with this issue.
andy
22 Jun, 2018
Hi Lokesh, What is the url you try to view when in xampp server? Do you have a real domain url? I just wonder if you add the real domain name, you still receive the same issue. That message clearly said the url you try to view does not match with the url you enter for the app.
Avesh
19 Sep, 2018
Hello, I am getting the message like: This app isn't verified This app hasn't been verified by Google yet. Only proceed if you know and trust the developer. If you’re the developer, submit a verification request to remove this screen. Learn more My Query : How I can resolved the above issue?
andy
22 Sep, 2018
I just changed the HTTP to HTTPS for the site and I didn't add the https://bytutorial.com into the whitelist. I just added it now, it may take a while for Google to allow it. You can try it after 30 mins. Let me know if the problem still exists.
Jer
17 Nov, 2018
Hi, great tutorial but I have a question regarding the upload file. It's there any way to make it multiple uploads and add "filename" to the progress event? See the image link below. Thank you! :) https://i.imgur.com/S6xmZu3.png
andy
21 Nov, 2018
Hi Jer, Yes it is possible, actually I have created some sample scripts for multiple upload. https://bytutorial.com/blogs/aspnet/upload-multiple-files-using-jquery-and-generic-handler You can actually modify the javascript upload and use a counter to identify if each individual upload has already been completed.
Tom
04 Dec, 2018
Thank you for sharing this tutorial. I am able to use it successfully. Question: can you provide assistance for working with Google TEAM DRIVE? I would like to modify this tutorial to upload files to a specific TEAM DRIVE. Thank you! Tom
andy
06 Dec, 2018
Hi Tom, Unfortunately, I haven't played around with Google Team Drive yet.
Gustavo Severo
29 Jan, 2019
Hi Andy, How can i get the titles of any documents in google drive, please? I would like to get the title when i click in i of information. How can i do that? Thank you so much.
andy
29 Jan, 2019
Hi Gustavo, I just submit verification to Google, as the demo link has been unauthorized by Google now. When you develop the code, just look for the function name called buildFiles. In the code, are you able to write the following code? console.write(DRIVE_FILES[i]); Then view the result in your web development console and see if you view any field property named title?
Thea
04 Feb, 2019
Hello Andy, Thank you so much for this tutorial! I have a few questions though: 1. Is there any chance that you can help me with incorporating Team Drive with it? 2. How do I automatically go to a certain folder after logging in? Specifically, how do I retrieve the folder ID given the folder name upon login? Because I know that you have to change the global variable FOLDER_ID for this, I just don't know the ID of the folder that I want to use (hope my explanation made sense haha) Many thanks! :)
andy
04 Feb, 2019
Hi Thea, I actually do not have any time yet to spend on the Google Team Drive. So I could not help this time, probably in the future. Regarding with the specific folder, probably the best you set to root first, then you can try to perform a loop to get a list of available folder. Once you get the list of the folder id, you can specify it directly. Hope it helps.
Mae
13 Feb, 2019
Hello, How do I sort the files alphabetically? And how would I separate the files from the folders, just like how the Google Drive page displays files? Thank you.
andy
13 Feb, 2019
Hi Mae, Have a look into the Google documentation. There is an option called orderBy. https://developers.google.com/drive/api/v2/reference/files/list. You can sort by title if you want. The example I gave is based on a folder tree structure. In order to get files, you need to access the parent folder first.
Thea
07 Mar, 2019
Hello again! Would you know how to open the files in another tab when you click them from the display (without downloading them)? Thank you!
Great Boss
09 Sep, 2019
Very good :-)
Sanjay
13 Sep, 2019
Hi Andy, I am using no of files in 1000, but it returns only 440 items. Is there any other way to get 1000 items or greater than that. I set like below // In global variable var NO_OF_FILES = 1000; // In getFiles() function var request = gapi.client.drive.files.list({ 'maxResults': NO_OF_FILES, 'orderBy' : 'modifiedDate asc' }); Please help me in this case. Thanks in advance.
sky lee
20 Sep, 2019
Hello, Thank you for your document! It works very well in Explorer. But not in Chrome. All hided in Chrome and nothing showed. Do you have any idea about this? Thank you!
Immad
04 Oct, 2019
it showing error in uploading documents MediaUploader not defined
andy
05 Oct, 2019
Hi Immad, the MediaUploder class is defined under upload.js file. Just double check on your console browser if there is any conflict in Javascript.
Immad Javed
07 Oct, 2019
how to make it without login?
andy
08 Oct, 2019
You always have to login for the web app.
Immad Javed
31 Oct, 2019
how can i access my shared drives in it kindly help
Rigal
01 Dec, 2019
Hello Andy, Thank you so much for this great tutorial. I have spent many hours to share uploaded files but didn't find any solution. I found a share button https://developers.google.com/drive/api/v3/share-button Would you please guide how to add the share button on each file? Thanks
Rigal Patel
06 Dec, 2019
Hello, I want to access all files(upload, delete, share) using a Google service account. Would you please suggest which changes required in the above code ? Thanks
andy
05 Jan, 2020
Hi Rigal, Have a look into the function buildFiles. This is where how the list of files are built and displayed as html function.
akshaya
26 Feb, 2020
please explain me how to integrate Drive UI's "Open with" menu item. https://developers.google.com/drive/api/v3/about-apps
Marcus
29 Apr, 2021
Hey Andy! Thank you so much for the tutorial. We examined everything you said but we keep getting an error in return. This is the message we are getting: Uncaught TypeError: Cannot read property 'authorize' of undefined Any idea of what that might be? Thank you! Best, Marcus.
andy
20 May, 2021
Hi Marcus, Maybe you forgot to load the API library?
Arvind
20 May, 2021
Hi Andy, Thanks a lot for this informative post. I am trying to use it to display files in my google drive on my blog. When I run the script, I get an error from getFiles() saying: Error: 5: The granted scopes do not give access to all of the requested spaces. I changed SCOPES to var SCOPES = ['https://www.googleapis.com/auth/drive.readonly','profile']; and gave permission to both .../auth/userinfo.profile and .../auth/drive.readonly from the add or remove scopes button. I shared a particular folder on my Google Drive and used the garbled part of the link as FOLDER_ID and its name as FOLDER_NAME. Any idea what could be wrong? Thanks, Arvind
andy
20 May, 2021
Hi Arvind, based on the error, it told you that there is an issue with permission access. I would suggest trying to give full access first to eliminate the possible issue rather than read. See if it works first.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Blogs

Google Analytics API Tutorial using JavaScript

In this tutorial you will learn how to access Google Analytics API using javascript We will use Oauth2 to access user account analytics and a combination of Google Analytics version 3 to get the list of account summaries and version ...

Related Tutorials