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"));
}
