Multi upload file to Google drive

 



คุณสมบัติ

  • ไม่จำกัดชนิดของไฟล์ 
  • อัพได้ครั้งละหลายไฟล์
  • กำหนดจำนวนสูงสุดในการอัพไฟล์ได้
  • แยกโฟลเดอร์ย่อยตามยูสเซอร์
  • ตั้งชื่อโฟลเดอร์ย่อยตามอีเมล์ของยูสเซอร์
  • บันทึกรายละเอียดลง google sheet


code.gs

const rootFolderId = 'xxxxxxxx';  // Change your folder Id !!!!!!!!!!!!!!!!!!!

/** The function returns an HTML service HtmlOutput object **/
function doGet() {
  return HtmlService.createTemplateFromFile("index").evaluate()
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}

/** Create folder in google drive **/
function createFolder(folderName) {
  try {
    const parentFolder = DriveApp.getFolderById(rootFolderId);
    const folders = parentFolder.getFoldersByName(folderName);
    let folder;
    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = parentFolder.createFolder(folderName);
    }
    return {
      'folderId' : folder.getId()
    }
  } catch (e) {
    return {
      'error' : e.toString()
    }
  }
}


/** upload file to google drive **/
function uploadFile(base64Data, fileName, folderId) {
  try {
    const splitBase = base64Data.split(','), type = splitBase[0].split(';')[0]
        .replace('data:', '');
    const byteCharacters = Utilities.base64Decode(splitBase[1]);
    const bobFile = Utilities.newBlob(byteCharacters, type);
    bobFile.setName(fileName);

    const folder = DriveApp.getFolderById(folderId);
    const files = folder.getFilesByName(fileName);
    let file
    while (files.hasNext()) {
      // delete existing files with the same name.
      file = files.next()
      file.setTrashed(true);
    }
    file = folder.createFile(bobFile)
    file_Name = file.getName()
    file_Url = file.getUrl()
    return {
      'file_Name' : file_Name,
      'file_Url' : file_Url
    }
  } catch (e) {
    return {
      'error' : e.toString()
    };
  }
}

/** save data to sheet **/
function recordData(sData){
  const datenow = new Date()
  sData.splice(0, 0, datenow)
  const sht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data")
        sht.appendRow(sData)
}

index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
 
  </head>
  <body>
    <div class="container">
      <form id="uploadForm" class="row g-3">
        <div class="mb-3 clo-md-6">
          <label for="name" class="form-label">Email address</label>
          <input type="text" class="form-control" id="name" name="name">
        </div>
        <div class="mb-3 clo-md-6">
          <label for="myfile" class="form-label">Choose File</label>
          <input type="file" class="form-control" id="myfile" name="myfile" multiple>
        </div>
        <button class="btn btn-primary" onclick="uploadFiles()">
          Send
        </button>
      </form>
    </div>
    <div id="output"></div>


    <script>

    const maxfile = 5 ;
    let numUploadsdone = 0
    let numUploadstotal = 0
    let folderName = ''
    let allFiles
    let sData = []
/** save data to sheet **/
    function uploadFiles() {
      event.preventDefault();
      folderName =document.getElementById('name').value
      allFiles = document.getElementById('myfile').files
      numUploadstotal = allFiles.length;
      if (numUploadstotal == 0 || folderName == "") {
        window.alert('No selected!');
      } else {
        if(maxfile < numUploadstotal ){
          alert("Upload no more than "+maxfile+" files.")
        }else{
          sData.push(folderName)
          google.script.run.withSuccessHandler(createFolder_withSuccessHandler)
.createFolder(folderName);
        }
      }
    }


/** Loop upload files to drive **/
    function createFolder_withSuccessHandler(data){
        for (let i = 0; i < allFiles.length; i++) {          
            uploadFile(allFiles[i], data.folderId);
        }
    }

/** Upload file to drive **/
    function uploadFile(file, folderId) {
      let reader = new FileReader();
      reader.onload = function(e) {
        let content = reader.result;
        document.getElementById('output').innerHTML = 'uploading '
            + file.name + '...';          
        google.script.run.withSuccessHandler(onFileUploaded)
            .uploadFile(content, file.name, folderId);
      }
      reader.readAsDataURL(file);
    }


/** Show upload status **/
    function onFileUploaded(r) {
      numUploadsdone++;
      sData.push(r.file_Url)
      document.getElementById('output').innerHTML = 'uploaded '
          + r.file_Name + '<br>' + numUploadsdone + '/'
          + numUploadstotal + ' files';
      if (numUploadsdone == numUploadstotal) {
        google.script.run.withSuccessHandler().recordData(sData)
        document.getElementById('output').innerHTML = 'Upload '
            + numUploadstotal + ' files completed.';
        numUploadsdone = 0;
        document.getElementById('output').innerHTML = ''
        document.getElementById('uploadForm').reset()
        allFiles  = []
        sData = []
      }
    }

    </script>

  </body>
</html>

แสดงความคิดเห็น (0)
ใหม่กว่า เก่ากว่า