The purpose of the code is to upload files to Google Drive from a web app programmatically using JavaScript. The part that uploads documents is working okay, but the video part is still not working. I still need help with getting the binary data from the array buffer. I'd like to ask for suggestions on how to improve my code and finally get it to work. Thanks!
Function attached to a button with an event listener
async function uploadVideoFile(){
let input = document.getElementById('upload-video');
let file = input.files[0];
let res = await getFiles(file).catch(err => alert(err.message));
google.script.run
.withSuccessHandler(response => {
//console.log(response)
})
.withFailureHandler(response => {
//console.log(response)
})
.uploadToGoogleDrive(res);
} //CLOSES FUNCTION
Function for getting files
function getFiles(file) {
return new Promise((resolve, reject) => {
let data;
let obj = {};
const fr = new FileReader();
fr.onload = e => {
if(!file) return;
if(file.type.includes('video')){
let chars = new Uint8Array(file);
let CHUNK_SIZE = 0x8000;
let index = 0;
let length = chars.length;
let result = '';
let slice;
while (index < length) {
slice = chars.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
data = new Uint8Array(fr.result);
let str = binArrayToString(data.buffer)
obj = { binary: str, mimeType: file.type, fileName: file.name };
}else{ //If not video
data = e.target.result.split(",");
obj = { binary: data[1], mimeType: data[0].match(/:(\w.+);/)[1], fileName: file.name };
}
resolve(obj);
}
if (file) {
if(file.type.includes('video')){
fr.readAsArrayBuffer(file);
}else{
fr.readAsDataURL(file);
}
} else {
reject("No file");
}
});
} //CLOSES FUNCTION
Code for converting array buffer to string
let binArrayToString = function(binArray) {
let str = "";
for (let i = 0; i < binArray.length; i++) {
str += String.fromCharCode(parseInt(binArray[i]));
}
return str;
} //CLOSES FUNCTION
Server-side function for uploading to Google Drive
function uploadToGoogleDrive(obj){
const FOLDER_ID = '';
let blob = Utilities.newBlob(Utilities.base64Decode(obj.binary), obj.mimeType, obj.fileName);
let folder = DriveApp.getFolderById(FOLDER_ID);
folder.createFile(blob).getId();
} //CLOSES FUNCTION