Hey Jon - I’ve managed to get a simple file upload working!!! If you’ve followed the first part of that tutorial you should have a client id. You’ll need to replace YOUR-CLIENT-ID-HERE below with that
Also, make sure that you’ve enabled Google Drive at https://console.cloud.google.com/marketplace/product/google/drive.googleapis.com
Hopefully this will work for you. It should take any kind of file. I tried several and they all worked fine. Oh - if you want to put them into a specific folder you can get the folder id from the url of the folder and replace ‘root’ below.
LMK how you go. And if you get it all pretty and working with error handling and all that good stuff I’d love the code. Thx.
<html>
<head>
<script src="dmxAppConnect/dmxAppConnect.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</head>
<body is="dmx-app" id="Drive">
<h1>Google Drive using Google Identity Services</h1>
<input id="inputUpload" type="file">
<button onclick="getToken();">Get access token</button> <br><br>
<button onclick="uploadFile();">Upload File</button> <br><br>
<button onclick="revokeToken();">Revoke token</button>
<div id="content"></div>
<script>
//Authorization
var client;
var access_token;
function initClient() {
client = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR-CLIENT-ID-HERE',
scope: 'https://www.googleapis.com/auth/drive.file',
callback: (tokenResponse) => {
access_token = tokenResponse.access_token;
},
});
}
function getToken() {
client.requestAccessToken();
}
function revokeToken() {
google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
}
//file upload
async function uploadFile() {
const fileToUpload = inputUpload.files[0];
var metadata = {
name: fileToUpload.name,
mimeType: fileToUpload.type,
'parents': ['root'], // Folder ID at Google Drive which is optional
};
var accessToken = access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
document.getElementById('content').innerHTML = "File uploaded successfully. The Google Drive file id is <b>" + xhr.response.id + "</b>";
document.getElementById('content').style.display = 'block';
};
xhr.send(form);
}
</script>
<script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
</body>
</html>