javascript 使用 Google App Script 将多个文件上传到 Google Drive

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31126181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:19:44  来源:igfitidea点击:

Uploading Multiple Files to Google Drive with Google App Script

javascripthtmlgoogle-apps-script

提问by bobatapioca

I'm trying to upload multiple files at once with my app. It recognizes when there are 2 or more files being selected. However, it will only upload the 1st file that is selected to my drive. Also (although quite minor), I was wondering how I can change my textarea font to be Times New Roman to stay consistent with the rest of the font.

我正在尝试使用我的应用程序一次上传多个文件。它会识别何时选择了 2 个或更多文件。但是,它只会将所选的第一个文件上传到我的驱动器。另外(虽然很小),我想知道如何将我的 textarea 字体更改为 Times New Roman 以与字体的其余部分保持一致。

Code.gs

代码.gs

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

function uploadFiles(form) {

  try {
    var foldertitle = form.zone + ' | Building: ' + form.building + ' | ' + form.propertyAddress + ' | ' + form.attachType;
    var folder, folders = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs");
    var createfolder = folders.createFolder(foldertitle);
    folder = createfolder;
    var blob = form.filename;
    var file = folder.createFile(blob);
    file.setDescription(" " + form.fileText);

    return "File(s) uploaded successfully! Here is the link to your file(s):     " + folder.getUrl();

  } catch (error) {
    Logger.log('err: ' + error.toString());
    return error.toString();
  }

}

function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
  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(nomeArq);

    var file = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs").createFile(ss);

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

form.html

表单.html

<body>
  <div id="formcontainer">

    <label for="myForm">Facilities Project Database Attachment Uploader:</label>

    <br><br>


    <form id="myForm"> 
      <label for="myForm">Project Details:</label>
      <div>
        <input type="text" name="zone" placeholder="Zone:">
      </div>
      <div>
        <input type="text" name="building" placeholder="Building(s):">
      </div>
      <div>
        <input type="text" name="propertyAddress" placeholder="Property Address:">
      </div>
      <div>

      <label for="fileText">Project Description:</label>

          <TEXTAREA name="projectDescription" 
          placeholder="Describe your attachment(s) here:"
          style ="width:400px; height:200px;"
          ></TEXTAREA>


      </div> 
      <br>


      <label for="attachType">Choose Attachment Type:</label>
      <br>
      <select name="attachType">
        <option value="Pictures Only">Picture(s)</option>
        <option value="Proposals Only">Proposal(s)</option>
        <option value="Pictures & Proposals">All</option>
      </select>
      <br>

      <label for="myFile">Upload Attachment(s):</label>
      <br>


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

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


    </form>
  </div>

  <div id="output"></div>

  <script>
    function iteratorFileUpload() {
        var allFiles = document.getElementById('myFile').files;

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

    // Send each file one at a time
    var i=0;
    for (i=0; i < allFiles.total; i+=1) {
      console.log('This iteration: ' + i);
      sendFileToDrive(allFiles[i]);
          };
        };
      };

    function sendFileToDrive(file) {
        var reader = new FileReader();
        reader.onload = function (e) {
        var content = reader.result;
        console.log('Sending ' + file.name);

        google.script.run
          .withSuccessHandler(fileUploaded)
          .uploadArquivoParaDrive(content, file.name, currFolder);
     }

      reader.readAsDataURL(file);
     };
  </script>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
  // Upload de arquivo dentro das pastas Arquivos Auxiliares
    function iterarArquivosUpload() {
    var arquivos = document.getElementById('inputUpload').files;

    if (arquivos.length == 0) {
        alert('No file selected!');
    } else {
        //Show Progress Bar
        numUploads.total = arquivos.length;
        $('.progressUpload').progressbar({
            value : false
        });
        $('.labelProgressUpload').html('Preparando arquivos para upload');

        // Send each file at a time
        for (var arqs = 0; arqs < numUploads.total; arqs++) {
            console.log(arqs);
            enviarArquivoParaDrive(arquivos[arqs]);
        }
    }
}

function enviarArquivoParaDrive(arquivo) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        console.log('Sending ' + arquivo.name);
        google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
    }
    reader.readAsDataURL(arquivo);
}

function updateProgressbar( idUpdate ){
   console.log('Received: ' + idUpdate);
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $('.progressUpload').progressbar({value: porc });
   $('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      uploadsFinished();
      numUploads.done = 0;
   };
}
</script>

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

  </script>

  <style>
    body {
      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;
    }
  </style>
</body>

回答by barragan

I know this question is old, but after finding it and related ones, I was never able to get the multiple file upload working. So after a lot of banging my head against walls, I wanted to post a full example (.html and .gs) in case anyone in the future is looking for one to get started. This is working when I deploy it right now and will hopefully work for other people out there. Note that I just hardcoded the folder in the drive to use in the code.gs file, but that can be easily changed.

我知道这个问题很老,但是在找到它和相关问题之后,我永远无法让多文件上传工作。所以在我的头撞墙很多次之后,我想发布一个完整的例子(.html 和 .gs),以防将来有人正在寻找一个开始。当我现在部署它时,这是有效的,并且希望对其他人有效。请注意,我只是硬编码了驱动器中的文件夹以在 code.gs 文件中使用,但这可以轻松更改。

form.html:

表单.html:

<body>
  <div id="formcontainer">

    <label for="myForm">Facilities Project Database Attachment Uploader:</label>

    <br><br>


    <form id="myForm"> 
      <label for="myForm">Project Details:</label>
      <div>
        <input type="text" name="zone" placeholder="Zone:">
      </div>
      <div>
        <input type="text" name="building" placeholder="Building(s):">
      </div>
      <div>
        <input type="text" name="propertyAddress" placeholder="Property Address:">
      </div>
      <div>

      <label for="fileText">Project Description:</label>

          <TEXTAREA name="projectDescription" 
          placeholder="Describe your attachment(s) here:"
          style ="width:400px; height:200px;"
          ></TEXTAREA>


      </div> 
      <br>


      <label for="attachType">Choose Attachment Type:</label>
      <br>
      <select name="attachType">
        <option value="Pictures Only">Picture(s)</option>
        <option value="Proposals Only">Proposal(s)</option>
        <option value="Pictures & Proposals">All</option>
      </select>
      <br>

      <label for="myFile">Upload Attachment(s):</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 = 'Something';
        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 ){
      //uploadsFinished();
      numUploads.done = 0;
   };
}
</script>

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

  </script>

  <style>
    body {
      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>

code.gs:

代码.gs:

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

function uploadFileToDrive(base64Data, fileName) {
  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 = "Something"; // 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();
  }
}

回答by Ryan

Updated For May 2017

2017 年 5 月更新

I updated and improved barragan's answer.

我更新并改进了巴拉甘的答案。

Advantages:

好处:

  1. Allows users to create a subfolder name to contain all the files uploaded during this session
  2. Ensures that these subfolders all exist within one specified folder within your Google Drive
  3. The page/form is mobile-responsive
  1. 允许用户创建子文件夹名称以包含此会话期间上传的所有文件
  2. 确保这些子文件夹都存在于您的 Google Drive 中的一个指定文件夹中
  3. 页面/表单是移动响应的

You can start with this examplejust to create the script and get to know the basics.

您可以从这个示例开始,只是为了创建脚本并了解基础知识。

Then you can completely replace form.htmlwith this:

然后你可以用这个完全替换form.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>
            Send Files
        </title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>        
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
        <script>

            $(document).ready(function () {

                function afterSubfolderCreated(subfolderId) {
                    console.log(subfolderId);
                    console.log(allFiles);
                    numUploads.total = allFiles.length;
                    $('#progressbar').progressbar({
                        value: false
                    });
                    $(".progress-label").html('Preparing files for upload');
                    for (var i = 0; i < allFiles.length; i++) {
                        console.log(i);
                        sendFileToDrive(allFiles[i], subfolderId);
                    }
                }

                function sendFileToDrive(file, subfolderId) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var content = reader.result;
                        console.log('Sending ' + file.name);
                        google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, subfolderId);
                    }
                    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) {                        
                        numUploads.done = 0;
                        $(".progress-label").text($(".progress-label").text() + ': FINISHED!');
                        $("#progressbar").after('(Optional) Refresh this page if you remembered other screenshots you want to add.');//<a href="javascript:window.top.location.href=window.top.location.href"> does not work
                    }
                }

                function fileUploaded(status) {
                    document.getElementById('myForm').style.display = 'none';
                    document.getElementById('output').innerHTML = status;
                }
                var numUploads = {};
                numUploads.done = 0;
                numUploads.total = 0;
                var allFiles;
                var frm = $('#myForm');
                frm.submit(function () {
                    allFiles = document.getElementById('myFile').files;
                    if (!frm.checkValidity || frm.checkValidity()) {
                        if (allFiles.length == 0) {
                            alert('Error: Please choose at least 1 file to upload.');
                            return false;
                        } else {
                            frm.hide();
                            var subfolderName = document.getElementById('myName').value;
                            $.ajax({
                                url: '',//URL of webhook endpoint for sending a Slack notification
                                data: {
                                     title: subfolderName + ' is uploading screenshots',
                                     message: ''
                                }
                            });
                            google.script.run.withSuccessHandler(afterSubfolderCreated).createSubfolder(subfolderName);
                            return false;
                        }
                    } else {
                        alert('Invalid form');
                        return false;
                    }
                });
            });//end docReady
        </script>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <style>
            body {
                padding: 20px;
                margin: auto;
                font-size: 20px;
            }
            label{
                font-weight: bold;
            }
            input{
                font-size: 20px;
                padding: 5px;
                display: inline-block;
                margin-bottom: 10px;
                -webkit-box-sizing: border-box;
                ?-moz-box-sizing: border-box;
                box-sizing: border-box;
            }
            .hint{
                font-size: 90%;
                color: #666;
            }
            select {
                margin: 5px 0px 15px 0px;
            }
            input[type="file"] {
                padding: 5px 0px 15px 0px;
            }
            #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;
            }
            li{
               padding: 10px;
            }
            @media only screen and (max-width : 520px) {
                #logo {
                    max-width: 100%;
                }
            }
        </style>
    </head>
    <body>
        <p>
            <img src="" id="logo">
        </p>
        <p>This webpage allows you to send me screenshots of your dating profiles.</p>
        <ol>
            <li>
                In each of your dating apps, take a screenshot <a href="https://www.take-a-screenshot.org/" target="_blank">(how?)</a> of every part of every page of your profile.
            </li>
            <li>
                Do the same for each of your photos (at full resolution).
            </li>
            <li>
                In the form below, type your first name and last initial (without any spaces or special characters), such as SallyT.
            </li>
            <li>
                Then click the first button and select all of your screenshot images (all at once).
            </li>
            <li>
                Finally, press the last button to send them all to me!
            </li>
        </ol>
        <form id="myForm"> 
            <div>
                <label for="myName">Your first name and last initial:</label> 
            </div>
            <div>
                <input type="text" name="myName" id="myName" placeholder="SallyT" required pattern="[a-zA-Z]+" value=""> 
                </div>
                <div>
                    <span class="hint">(No spaces or special characters allowed because this will determine your folder name)</span>
                </div>            
            <div style="margin-top: 20px;">
                <label for="myFile">Screenshot image files:</label>

                <input type="file" name="filename" id="myFile" multiple>
            </div>
            <div style="margin-top: 20px;">
                <input type="submit" value="Send File(s) ?" >
            </div>
        </form>

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


    </body>
</html>

And completely replace server.gswith this:

并用这个完全替换server.gs

function doGet() {
  var output = HtmlService.createHtmlOutputFromFile('form');
  output.addMetaTag('viewport', 'width=device-width, initial-scale=1');// See http://stackoverflow.com/a/42681526/470749
  return output.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName, subfolderId) {
  Logger.log(subfolderId);
  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 subfolder = DriveApp.getFolderById(subfolderId);
    var file = subfolder.createFile(ss);
    Logger.log(file);
    return file.getName() + ' at ' + file.getUrl();
  } catch(e){
    return 'createFile Error: ' + e.toString();
  }
}

function createSubfolder(subfolderName){
  var dropbox = subfolderName + Utilities.formatDate(new Date(), "US/Eastern", "_yyyy-MM-dd");
    Logger.log(dropbox);
    var parentFolderId = "{ID such as 0B9iQ20nrMNYAaHZxRjd}";
    var parentFolder = DriveApp.getFolderById(parentFolderId);
    var folder;
    try {
      folder = parentFolder.getFoldersByName(dropbox).next();      
    }
    catch(e) {
      folder = parentFolder.createFolder(dropbox);
    }
    Logger.log(folder);
  return folder.getId();
}

回答by Charles Plucker

Joining the pile of older answers, but this really helped me when I implemented my own file multi upload for getting files into Google Drive using the DriveApp V3 api.

加入一堆较旧的答案,但是当我实现自己的文件多上传以使用 DriveApp V3 api 将文件导入 Google Drive 时,这确实帮助了我。

I wrote and posted my own solution here: https://github.com/CharlesPlucker/drive-multi-upload/

我在这里写并发布了我自己的解决方案:https: //github.com/CharlesPlucker/drive-multi-upload/

Improvements: - Handles multiple files sequentially - Handles large > 50MB files - Validation

改进: - 顺序处理多个文件 - 处理大于 50MB 的大文件 - 验证

I wrapped my google api calls into promises since I was running into timing issues when creating a folder and immediately trying to fetch it by name reference. Each one of my promises will only resolve when its file is fully uploaded. To get that working I had to use a Promise Factory. I'll be glad to explain this code if the need arises!

我将我的 google api 调用封装到 promise 中,因为我在创建文件夹并立即尝试通过名称引用获取它时遇到了计时问题。我的每一个承诺只有在文件完全上传后才会解决。为了让它工作,我不得不使用一个 Promise 工厂。如果需要,我很乐意解释这段代码!

回答by Kriggs

You have to send a file at a time trough the script.run, here's my implementation with FileReaders/ReadAsURL, which makes the file a Base64 string, which can be easily passed around:

您必须通过 script.run 一次发送一个文件,这是我使用 FileReaders/ReadAsURL 的实现,它使文件成为 Base64 字符串,可以轻松传递:

Notes:

笔记:

  1. Dunno if it's necessary but I'm using IFRAME sandbox
  2. I left the progressBar in the code, you can remove it
  3. Everything must be OUTSIDE a form
  4. It accepts any file type
  1. 不知道是否有必要,但我正在使用 IFRAME 沙箱
  2. 我把progressBar留在代码里了,你可以去掉
  3. 一切都必须在表单之外
  4. 它接受任何文件类型

HTML:

HTML:

// Upload de arquivo dentro das pastas Arquivos Auxiliares
function iterarArquivosUpload() {
    var arquivos = document.getElementById('inputUpload').files;

    if (arquivos.length == 0) {
        alert('No file selected!');
    } else {
        //Show Progress Bar
        numUploads.total = arquivos.length;
        $('.progressUpload').progressbar({
            value : false
        });
        $('.labelProgressUpload').html('Preparando arquivos para upload');

        // Send each file at a time
        for (var arqs = 0; arqs < numUploads.total; arqs++) {
            console.log(arqs);
            enviarArquivoParaDrive(arquivos[arqs]);
        }
    }
}

function enviarArquivoParaDrive(arquivo) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        console.log('Sending ' + arquivo.name);
        google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
    }
    reader.readAsDataURL(arquivo);
}

function updateProgressbar( idUpdate ){
   console.log('Received: ' + idUpdate);
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $('.progressUpload').progressbar({value: porc });
   $('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      uploadsFinished();
      numUploads.done = 0;
   };
}

Code.GS

代码.GS

function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
  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(nomeArq);

    var file = DriveApp.getFolderById(idPasta).createFile(ss);

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

回答by Andy at Focallocal

as @barragan's answer here is the best answer i found after hours and hours of searching for a question many people were asking, i've done a bit of development to improve the design a bit for others as a thanks. still a few bugs and chrome seems to run out of memory and give up with any file over 100MB

由于@barragan 在这里的回答是我在数小时和数小时搜索许多人问的问题后找到的最佳答案,我已经做了一些开发以改进设计以感谢其他人。仍然有一些错误,chrome 似乎内存不足并放弃任何超过 100MB 的文件

here's a live version

这是现场版

server.gs

服务器.gs

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

function uploadFileToDrive(base64Data, fileName) {
  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 = "Something"; // 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();
  }
}
'

form.html

表单.html

<head>
    <base target="_blank">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Focallocal Uploader</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
  <div align="center">
    <p><img src="http://news.focallocal.org/wp-content/uploads/2015/03/FOCALLOCAL-Website-Text-Header.png" width="80%"></p> 
  </div> 
</head>

<body>


  <div id="formcontainer" width="50%">

    <label for="myForm">Focallocal Community G.Drive Uploader</label>

  <br>

  <br>
    <form id="myForm" width="50%"> 
      <label for="myForm">Details</label>
      <div>
        <input type="text" name="Name" placeholder="your name">
      </div>
      <div>
        <input type="text" name="gathering" placeholder="which fabulous Positive Action you're sending us">
      </div>
      <div>
        <input type="text" name="location" placeholder="the town/village/city and country month brightend by positivity">
      </div>
      <div>
        <input type="text" name="date" placeholder="date of the beautiful action">
      </div>
      <div  width="100%" height="200px">

      <label for="fileText">would you like to leave a short quote?</label>

          <TEXTAREA name="Quote" 
          placeholder="many people would love to share in your experience. if you have more than a sentence or two to write, why not writing an article the Community News section of our website?"         
          ></TEXTAREA>


      </div> 
      <br>


      <br>

      <label for="myFile">Upload Your Files:</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 = 'Something';
        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 ){
      //uploadsFinished();
      numUploads.done = 0;
   };
}
</script>

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

  </script>

  <style>
    body {
      max-width: 60%;
      padding: 20px;
      margin: auto;
    }
    input {
      display: inline-block;
      width: 50%;
      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: 40%;
    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>

i wasn't able to get the text fields to send an email with the details out, and ran out of time before working out how to hook them up to a Google Spreadsheet, so for the moment they don't record the information added

我无法获取文本字段以发送包含详细信息的电子邮件,并且在研究如何将它们连接到 Google 电子表格之前用完了时间,因此目前他们不记录添加的信息

as an added bonus, it looked fabulous with is in the form.html

作为额外的奖励,它看起来很棒,在 form.html 中

      <div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;">
      <a class="btn-floating btn-large red">
        <i class="large material-icons">menu</i>
      </a>
      <ul>
        <li><a class="btn-floating red"  href="https://focallocal-a-positive-action-movement.myshopify.com/" target="_blank" title="Pimp your Cool at the Positive Action Shop"><i class="material-icons">monetization_on</i></a></li>
        <li><a class="btn-floating blue"  href="https://www.youtube.com/user/Focallocal" target="_blank" title="Follow the Positive Action Youtube Channel"><i class="material-icons">video_library</i></a></li>
        <li><a class="btn-floating green" href="http://focallocal.org/" target="_blank" title="Read our About Us Page"><i class="material-icons">help</i></a></li>
      </ul>

   </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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
    <script src="https://gumroad.com/js/gumroad.js"></script>

i took it out again as some of the scripts being called in were causing issues. if anyone can fix them it they add a lot to the appearance and functionality of the form

我又把它拿出来了,因为一些被调用的脚本导致了问题。如果有人可以修复它们,它们会为表单的外观和功能增加很多

*edit: i've been playing around with it and only around half of the files sent seem to arrive, so there are still some issues with both of the codes here atm

*编辑:我一直在玩它,似乎只有大约一半的文件发送到了,所以这里的两个代码仍然存在一些问题 atm