Skip to content

Instantly share code, notes, and snippets.

@gabrielhpugliese
Created October 29, 2012 12:24
Show Gist options
  • Save gabrielhpugliese/3973245 to your computer and use it in GitHub Desktop.
Save gabrielhpugliese/3973245 to your computer and use it in GitHub Desktop.
google drive
var CLIENT_ID = '[%client_id%]';
var SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
gapi.auth.authorize(
{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
handleAuthResult);
}
/**
* Called when authorization server replies.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
var filePicker = document.getElementById('filePicker');
filePicker.style.visibility = '';
filePicker.onchange = uploadFile;
} else {
// No access token could be retrieved, force the authorization flow.
gapi.auth.authorize(
{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
handleAuthResult);
}
}
/**
* Start the file upload.
*
* @param {Object} evt Arguments from the file selector.
*/
function uploadFile(evt) {
gapi.client.load('drive', 'v2', function() {
var file = evt.target.files[0];
insertFile(file, applyFolder);
});
}
function applyFolder(file){
var folderId = '[%folder_id%]';
if (folderId)
insertFileIntoFolder(folderId, file.id);
alert('Your file was successfully uploaded');
}
/**
* Insert a file into a folder.
*
* @param {String} folderId ID of the folder to insert the file into.
* @param {String} fileId ID of the file to insert.
*/
function insertFileIntoFolder(folderId, fileId) {
var body = {'id': folderId};
var request = gapi.client.drive.parents.insert({
'fileId': fileId,
'resource': body
});
request.execute(function(resp) { });
}
/**
* Insert new file.
*
* @param {File} fileData File object to read data from.
* @param {Function} callback Function to call when the request is complete.
*/
function insertFile(fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = '\r\n--' + boundary + '\r\n';
const close_delim = '\r\n--' + boundary + '--';
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
var contentType = fileData.type || 'application/octet-stream';
var metadata = {
'title': fileData.name,
'mimeType': contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary=\'' + boundary + '\''
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
}
function upload_click(){
alert('Note: You will need to allow popups from this site and connect with your Google Account. After allowing the app, reload the page and click again.');
jQuery(this).toggle();
jQuery.getScript("https://apis.google.com/js/client.js?onload=handleClientLoad");
jQuery('#filePicker').css('display', '');
}
jQuery(document).ready(function(){
var upload_button = {
'style': 'height: 50px; width: 100px;',
'id': 'upload-btn'
},
div = '[%div%]',
$div = jQuery(div);
$div.append('<input type="file" id="filePicker" style="visibility: hidden; display: none;" />');
$div.append('<button style="'+upload_button['style']+'" id="'+upload_button['id']+'">Upload your file</button>');
jQuery('#'+upload_button['id']).click(upload_click);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment