Google Apps scrip

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

Published by

tuanitpro

Tôi là Lê Thanh Tuấn, và tôi chia sẻ những điều mình cho rằng nó là thú vị, hay giúp ích cho bạn!

Leave a Reply