Uploading Multiple Files to Google Drive with Google App Script

Hướng dẫn upload nhiều file trong Google App Script bằng Javascript, kết hợp HTML

Index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>Uploading Multiple Files to Google Drive with Google App Script</h1>
    
    <div>
        <input type="file" name="filesToUpload" id="filesToUpload" multiple>
        <input type="button" value="Submit" onclick="uploadFiles()">
    
    <br />
    <div id="output"></div>
    </div>
    
    
   <?!= include('Script'); ?>
  </body>
</html>


Code.gs

function doGet() {
   return HtmlService.createTemplateFromFile('Index').evaluate().setTitle("Upload files");
}
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}
function createFolder(parentFolderId, folderName) {
	try {
		var parentFolder = DriveApp.getFolderById(parentFolderId);
		var folders = parentFolder.getFoldersByName(folderName);
		var folder;
		if (folders.hasNext()) {
			folder = folders.next();
		} else {
			folder = parentFolder.createFolder(folderName);
		}
		return {
			'folderId' : folder.getId()
		}
	} catch (e) {
		return {
			'error' : e.toString()
		}
	}
}

function uploadFile(base64Data, fileName, folderId) {
	try {
		var splitBase = base64Data.split(','), type = splitBase[0].split(';')[0]
				.replace('data:', '');
		var byteCharacters = Utilities.base64Decode(splitBase[1]);
		var ss = Utilities.newBlob(byteCharacters, type);
		ss.setName(fileName);

		var folder = DriveApp.getFolderById(folderId);
		var files = folder.getFilesByName(fileName);
		var file;
		while (files.hasNext()) {
			// delete existing files with the same name.
			file = files.next();
			folder.removeFile(file);
		}
		file = folder.createFile(ss);
		return {
			'folderId' : folderId,
			'fileName' : file.getName()
		};
	} catch (e) {
		return {
			'error' : e.toString()
		};
	}
}

Script.html

<script>
		var rootFolderId = '0BzFoC9aU9gwFYXZkbUZiTHg2LVE';
		var numUploads = {};
		numUploads.done = 0;
		numUploads.total = 0;
		var folderName = 'Demo';
		function uploadFiles() {
			var allFiles = document.getElementById('filesToUpload').files;
			  
			
			if (allFiles.length == 0) {
				window.alert('No file selected!');
			} else {
				numUploads.total = allFiles.length;
				google.script.run.withSuccessHandler(createFolder_withSuccessHandler).createFolder(rootFolderId, folderName);
			}
		}
        function createFolder_withSuccessHandler(data){
            var allFiles = document.getElementById('filesToUpload').files;
            for (var i = 0; i < allFiles.length; i++) {						
						uploadFile(allFiles[i], data.folderId);
					}
        }
		function uploadFile(file, folderId) {
			var reader = new FileReader();
			reader.onload = function(e) {
				var content = reader.result;
				document.getElementById('output').innerHTML = 'uploading '
						+ file.name + '...';					
				google.script.run.withSuccessHandler(onFileUploaded)
						.uploadFile(content, file.name, folderId);
			}
			reader.readAsDataURL(file);
		}
		function onFileUploaded(r) {
			numUploads.done++;
			document.getElementById('output').innerHTML = 'uploaded '
					+ r.fileName + ' (' + numUploads.done + '/'
					+ numUploads.total + ' files).';
			if (numUploads.done == numUploads.total) {
				document.getElementById('output').innerHTML = 'All of the '
						+ numUploads.total + ' files are uploaded';
				numUploads.done = 0;
			}
		}	
</script>

Source code

Upload file trong Google Apps Script

Hướng dẫn sau đây giúp bạn upload một file từ máy của hình lên thư mục trên Google Drive của bạn thông qua Google Apps Script

Code.gs

// Ham upload file, nhận vào một file input
function uploadFileToGoogleDrive(fileInput) {
/* Name of the Drive folder where the files should be saved */
var dropbox = FOLDER_NAME;
var folder,folders = DriveApp.getFoldersByName("Ten_thu_muc_cua_ban"); //getFolderById, getFoldersByName

/* Find the folder, create if the folder does not exist */
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}

/* Get the file uploaded though the form as a blob */
var file = folder.createFile(fileInput);

/* Set the file description as the name of the uploader */
//file.setDescription("Uploaded by " + form.myName);

/* Return the download URL of the file once its on Google Drive */
var fileUrl=file.getUrl();
Logger.log(fileUrl)
return fileUrl;
}


// Ham thực thi Upload file. Data là một FormId
function doUploadFile(data){

 var myFile = data.myfile;
 if(typeof myFile !== 'undefined' && myFile!=null && myFile.length>0)
 { 
 return uploadFileToGoogleDrive(myFile);
 }
 return "";
}

Code HTML

 <form name="uploadfile" enctype="multipart/form-data" id="uploadForm">
     <label>Chọn file tải lên</label>
     <input type="file" name="myfile" id="myfile" />
     <button type="button" class="btn btn-primary" onclick="return doUploadFile();">Upload</button>
</form>

Code Javascript

function doUploadFile() { 
        google.script.run           
            .doUploadFile(document.getElementById("uploadForm"));

}