Blog‎ > ‎

Multiple File Upload to Google Drive Using Google Script

posted Jul 19, 2016, 8:18 PM by Christopher Furton   [ updated Jul 19, 2016, 8:19 PM ]
This script and form was developed for a project facilitating photo upload by professional photographers for a non-profit organization.  It creates a folder in Google Drive based off the text input of the photographer name and then uploads the user selected files.  This script was adapted from other available scripts on the Internet and customized to suit my needs.  If you are the originator of the script, please let me know and I'll give proper credit!

This is the contents of Server.gs:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('form')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName, dropbox) {
  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 dropbox = "WTELNSD2016"; // Folder Name
    var folder, folders = DriveApp.getFoldersByName(dropbox);

    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var file = folder.createFile(ss);

    return file.getName();
  }catch(e){
    return 'Error: ' + e.toString();
  }
}

And this is the form.html

<body>
  <div id="formcontainer"><center>
<img src="https://drive.google.com/uc?id=0B1FVNNdar_tpaklWSW15Rk1ld1U"><br></center>
    <label for="myForm"></label>

    <br><br>


    <form id="myForm">
      <label for="myForm">Photographer Name:</label>
      <div>
        <input type="text" name="pName" id="pName2" placeholder="Enter your name or company here">
      </div>
 
      <br>


      <label for="myFile">Upload Pictures: <br> (hold Shift or Ctrl to select more than one):</label>
      <br>


      <input type="file" name="filename" id="myFile" multiple>

      <input type="button" value="Submit" onclick="iteratorFileUpload()">


    </form>
  </div>

  <div id="output"></div>
<div id="progressbar">
    <div class="progress-label"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>

var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;

// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
    var allFiles = document.getElementById('myFile').files;

    if (allFiles.length == 0) {
        alert('No file selected!');
    } else {
        //Show Progress Bar

        numUploads.total = allFiles.length;
        $('#progressbar').progressbar({
        value : false
        });//.append("<div class='caption'>37%</div>");
        $(".progress-label").html('Preparing files for upload');
        // Send each file at a time
        for (var i = 0; i < allFiles.length; i++) {
            console.log(i);
            sendFileToDrive(allFiles[i]);
        }
    }
}

function sendFileToDrive(file) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        console.log('Sending ' + file.name);
       
        var currFolder = document.getElementById('pName2').value;
        console.log('Folder name ' + currFolder);
        google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
    }
    reader.readAsDataURL(file);
}

function updateProgressbar( idUpdate ){
   console.log('Received: ' + idUpdate);
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $("#progressbar").progressbar({value: porc });
   $(".progress-label").text(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      document.write("Upload Complete")
      //uploadsFinished();
      numUploads.done = 0;
   };
}
</script>

  <script>
    function fileUploaded(status) {
      document.getElementById('myForm').style.display = 'none';
      document.getElementById('output').innerHTML = status;
    }

  </script>

  <style>
    body {
      font-family: verdana;
      max-width: 400px;
      padding: 20px;
      margin: auto;
    }
    input {
      display: inline-block;
      width: 100%;
      padding: 5px 0px 5px 5px;
      margin-bottom: 10px;
      -webkit-box-sizing: border-box;
      ‌​ -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    select {
      margin: 5px 0px 15px 0px;
    }
    input[type="submit"] {
      width: auto !important;
      display: block !important;
    }
    input[type="file"] {
      padding: 5px 0px 15px 0px !important;
    }
#progressbar{
    width: 100%;
    text-align: center;
    overflow: hidden;
    position: relative;
    vertical-align: middle;

}
.progress-label {
      float: left;
margin-top: 5px;
      font-weight: bold;
      text-shadow: 1px 1px 0 #fff;
          width: 100%;
    height: 100%;
    position: absolute;
    vertical-align: middle;
    }
  </style>
</body>

About the Author

Christopher Furton author bio picture
Christopher Furton

is an Information Technology Professional with over 12 years in the industry.  He attended The University of Michigan earning a B.S. in Computer Science and recently completed a M.S. in Information Management from Syracuse University.  His career includes managing small to medium size IT infrastructures, service desks, and IT operations.  Over the years, Christopher has specialized in Cyber Security while working within the Department of the Defense and the United States Marine Corps. His research topics include vulnerability management, cyber security governance, privacy, and cyber risk management.  He holds active IT Certifications including the CISSP, CEH, ITIL Foundations, Security+CE and Network+CE.  He can be found on , , and .  

Additional information available on Christopher Furton's website at
ċ
Upload.json
(6k)
Christopher Furton,
Jul 19, 2016, 8:24 PM
Comments