Last active
October 20, 2022 12:17
-
-
Save mkaminsky11/8624150 to your computer and use it in GitHub Desktop.
How to manipulate Google Drive files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Download a file | |
*/ | |
function downloadFile(fileId) { | |
var request = gapi.client.drive.files.get({ | |
'fileId': fileId | |
}); | |
request.execute(function(resp) { | |
window.location.assign(resp.webContentLink); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Get contents | |
*/ | |
function getContentOfFile(theID){ //gets the content of the file | |
current = theID; | |
gapi.client.request({'path': '/drive/v2/files/'+theID,'method': 'GET',callback: function ( theResponseJS, theResponseTXT ) { | |
var myToken = gapi.auth.getToken(); | |
var myXHR = new XMLHttpRequest(); | |
myXHR.open('GET', theResponseJS.downloadUrl, true ); | |
myXHR.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token ); | |
myXHR.onreadystatechange = function( theProgressEvent ) { | |
if (myXHR.readyState == 4) { | |
if ( myXHR.status == 200 ) { | |
var code = myXHR.response; | |
} | |
} | |
} | |
myXHR.send(); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Now to create a new file | |
*/ | |
function insertNewFile(folderId) { | |
var content = " "; | |
var FolderId = ""; | |
var contentArray = new Array(content.length); | |
for (var i = 0; i < contentArray.length; i++) { | |
contentArray[i] = content.charCodeAt(i); | |
} | |
var byteArray = new Uint8Array(contentArray); | |
var blob = new Blob([byteArray], {type: 'text/plain'}); | |
insertFile(blob, fileInserted, folderId); | |
} | |
function fileInserted(d) { | |
setPercent("100"); | |
var FI = FolderId; | |
if(FI !== myRootFolderId){ | |
insertFileIntoFolder(FI, d.id); | |
removeFileFromFolder(d.parents[0].id,d.id); | |
} | |
openFile(d.id); | |
} | |
function insertFileIntoFolder(folderId, fileId) { | |
var body = {'id': folderId}; | |
var request = gapi.client.drive.parents.insert({ | |
'fileId': fileId, | |
'resource': body | |
}); | |
request.execute(function(resp) { }); | |
} | |
function removeFileFromFolder(folderId, fileId) { | |
var request = gapi.client.drive.parents.delete({ | |
'parentId': folderId, | |
'fileId': fileId | |
}); | |
request.execute(function(resp) { }); | |
} | |
function insertFile(fileData, callback, folderId) { | |
setPercent("90"); | |
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': "untitled.txt", | |
'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) { | |
}; | |
} | |
request.execute(callback); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Check the permissions of a file | |
*/ | |
function getP(fileId) { | |
var request = gapi.client.drive.permissions.list({ | |
'fileId': fileId | |
}); | |
request.execute(function(resp) { | |
console.log(resp.items); | |
console.log(resp.items.length); | |
var ret = false; | |
for(i = 0; i < resp.items.length; i++){ | |
console.log(resp.items[i]); | |
if(resp.items[i].id === userId || resp.items[i].id === "anyone" || resp.items[i].id === "anyoneWithLink"){ | |
ret = true; | |
} | |
} | |
console.log(ret); | |
if(ret === false){ | |
//you don't have permission | |
} | |
else{ | |
//ok! | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Rename a file | |
*/ | |
function renameFile(fileId, newTitle) { | |
var body = {'title': newTitle}; | |
var request = gapi.client.drive.files.patch({ | |
'fileId': fileId, | |
'resource': body | |
}); | |
request.execute(function(resp) { | |
console.log('New Title: ' + resp.title); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
How to update a file | |
*/ | |
function saveFile(fileId, content){ | |
if(typeof content !== "undefined"){ | |
var contentArray = new Array(content.length); | |
for (var i = 0; i < contentArray.length; i++) { | |
contentArray[i] = content.charCodeAt(i); | |
} | |
var byteArray = new Uint8Array(contentArray); | |
var blob = new Blob([byteArray], {type: 'text/plain'}); | |
var request = gapi.client.drive.files.get({'fileId': fileId}); | |
request.execute(function(resp) { | |
updateFile(fileId,resp,blob,changesSaved); | |
}); | |
} | |
} | |
function updateFile(fileId, fileMetadata, fileData, callback) { | |
if(ok){ | |
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 base64Data = btoa(reader.result); | |
var multipartRequestBody = | |
delimiter + | |
'Content-Type: application/json\r\n\r\n' + | |
JSON.stringify(fileMetadata) + | |
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/' + fileId, | |
'method': 'PUT', | |
'params': {'uploadType': 'multipart', 'alt': 'json'}, | |
'headers': { | |
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"' | |
}, | |
'body': multipartRequestBody}); | |
if (!callback) { | |
callback = function(file) { | |
}; | |
} | |
request.execute(callback); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Get the title of a file | |
*/ | |
function getTitle(fileId){ | |
var request = gapi.client.drive.files.get({ | |
'fileId': fileId | |
}); | |
request.execute(function(resp) { | |
title = resp.title; | |
if(typeof title === 'undefined' || title === "undefined"){ | |
//error | |
return false; | |
} | |
document.getElementById('renameInput').value = title; | |
checkFileName(resp.title); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
How to refresh your access token (they expire every hour) | |
*/ | |
window.setInterval(function(){ | |
refreshToken(); | |
},3000000); //<--this is in milliseconds | |
function refreshToken() { | |
gapi.auth.authorize({'client_id': CLIENT_ID, 'scope': SCOPES.join(' '), 'immediate':true},tokenRefreshed); | |
//you have to get your client id and the proper scopes | |
window.setInterval(function(){ | |
refreshToken(); | |
},3000000); | |
} | |
function tokenRefreshed(result){ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Get user info | |
*/ | |
function user() { | |
var request = gapi.client.drive.about.get(); | |
request.execute(function(resp) { | |
try{ | |
var myRootFolderId = resp.rootFolderId; | |
var userName = resp.name; | |
var userUrl = resp.user.picture.url; | |
var userId = resp.user.permissionId; | |
var total_q = resp.quotaBytesTotal; | |
var user_q = resp.quotaBytesUsedAggregate; | |
} | |
catch(e){ | |
//error! | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay, the 'false' response goes away when I remove the 'alt: media' property from the argument object,
and I now get an object for the response. Is this a "pure" binary file, or a blob of some sort? I can't tell.
Thanks.