使用 Google App 脚本将多个文件上传到 Google Drive

Uploading Multiple Files to Google Drive with Google App Script(使用 Google App 脚本将多个文件上传到 Google Drive)
本文介绍了使用 Google App 脚本将多个文件上传到 Google Drive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

代码.gs

函数 doGet() {返回 HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME);}函数上传文件(表格){尝试 {var 文件夹标题 = form.zone + ' |建筑:'+ form.building +' |' + form.propertyAddress + ' |' + form.attachType;var 文件夹,文件夹 = DriveApp.getFolderById("0B7UEz7SKB72HfmNmNnlSM2NDTVVUSlloa1hZeVI0VEJuZUhSTmc4UXYwZjV1eWM5YXJPaGs");var createfolder = 文件夹.createFolder(文件夹标题);文件夹=创建文件夹;var blob = form.filename;var file = folder.createFile(blob);file.setDescription(" " + form.fileText);return "文件上传成功!这是您文件的链接:" + folder.getUrl();} 捕捉(错误){Logger.log('err:' + error.toString());返回错误.toString();}}函数上传ArquivoParaDrive(base64Data,nomeArq,idPasta){尝试{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);返回文件.getName();}捕捉(e){return '错误:' + e.toString();}}

form.html

<div id="formcontainer"><label for="myForm">设施项目数据库附件上传器:</label><br><br><form id="myForm"><label for="myForm">项目详情:</label>
<input type="text" name="zone" placeholder="Zone:"></div>
<input type="text" name="building" placeholder="Building(s):"></div>
<input type="text" name="propertyAddress" placeholder="房产地址:"></div>

<label for="fileText">项目描述:</label><TEXTAREA 名称="项目描述"placeholder="在此处描述您的附件:"样式=宽度:400像素;高度:200像素;"></TEXTAREA></div><br><label for="attachType">选择附件类型:</label><br><选择名称="attachType"><option value="仅限图片">图片</option><option value="仅限提案">提案</option><option value="图片&提案">全部</option></选择><br><label for="myFile">上传附件:</label><br><input type="file" name="filename" id="myFile" 多个><input type="submit" value="Submit" onclick="iteratorFileUpload()"></表格></div><div id="输出"></div><脚本>函数迭代器文件上传(){var allFiles = document.getElementById('myFile').files;if (allFiles.length == 0) {alert('没有选择文件!');} 别的 {//每次发送一个文件变量 i=0;for (i=0; i < allFiles.total; i+=1) {console.log('本次迭代:' + i);sendFileToDrive(allFiles[i]);};};};函数发送文件到驱动(文件){var reader = new FileReader();reader.onload = 函数 (e) {var content = reader.result;console.log('发送中' + file.name);google.script.run.withSuccessHandler(fileUploaded).uploadArquivoParaDrive(内容,文件名,currFolder);}reader.readAsDataURL(文件);};</脚本><script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><脚本>//上传 de arquivo dentro das Pastas Arquivos Auxiliares功能 iterarArquivosUpload() {var arquivos = document.getElementById('inputUpload').files;如果(arquivos.length == 0){alert('没有选择文件!');} 别的 {//显示进度条numUploads.total = arquivos.length;$('.progressUpload').progressbar({值:假});$('.labelProgressUpload').html('Preparando arquivos para upload');//一次发送每个文件for (var arqs = 0; arqs < numUploads.total; arqs++) {控制台.log(arqs);enviarArquivoParaDrive(arquivos[arqs]);}}}功能enviarArquivoParaDrive(arquivo){var reader = new FileReader();reader.onload = 函数 (e) {var content = reader.result;console.log('正在发送' + arquivo.name);google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);}reader.readAsDataURL(arquivo);}函数更新进度条(idUpdate){console.log('收到:' + idUpdate);numUploads.done++;var porc = Math.ceil((numUploads.done/numUploads.total)*100);$('.progressUpload').progressbar({value: porc });$('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);如果(numUploads.done == numUploads.total){上传完成();numUploads.done = 0;};}</脚本><脚本>功能文件上传(状态){document.getElementById('myForm').style.display = 'none';document.getElementById('output').innerHTML = status;}</脚本><风格>身体 {最大宽度:400px;填充:20px;边距:自动;}输入 {显示:内联块;宽度:100%;填充:5px 0px 5px 5px;边距底部:10px;-webkit-box-sizing:边框框;‌ -moz-box-sizing: 边框;box-sizing:边框框;}选择 {边距:5px 0px 15px 0px;}输入[类型=提交"] {宽度:自动!重要;显示:块!重要;}输入[类型=文件"] {填充:5px 0px 15px 0px !重要;}</风格></身体>

解决方案

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

form.html:

<div id="formcontainer"><label for="myForm">设施项目数据库附件上传器:</label><br><br><form id="myForm"><label for="myForm">项目详情:</label>

<input type="text" name="zone" placeholder="Zone:"></div>

<input type="text" name="building" placeholder="Building(s):"></div>

<input type="text" name="propertyAddress" placeholder="房产地址:"></div>

<label for="fileText">项目描述:</label><TEXTAREA 名称="项目描述"placeholder="在此处描述您的附件:"样式=宽度:400像素;高度:200像素;"></TEXTAREA></div><br><label for="attachType">选择附件类型:</label><br><选择名称="attachType"><option value="仅限图片">图片</option><option value="仅限提案">提案</option><option value="图片&提案">全部</option></选择><br><label for="myFile">上传附件:</label><br><input type="file" name="filename" id="myFile" 多个><input type="button" value="Submit" onclick="iteratorFileUpload()"></表格></div><div id="输出"></div><div id="进度条"><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><脚本>var numUploads = {};numUploads.done = 0;numUploads.total = 0;//将文件上传到驱动器的文件夹中//设置为将它们全部发送到一个文件夹(在 .gs 文件中指定)函数迭代器文件上传(){var allFiles = document.getElementById('myFile').files;if (allFiles.length == 0) {alert('没有选择文件!');} 别的 {//显示进度条numUploads.total = allFiles.length;$('#progressbar').progressbar({值:假});//.append("<div class='caption'>37%</div>");$(".progress-label").html('准备上传文件');//一次发送每个文件for (var i = 0; i < allFiles.length; i++) {控制台.log(i);sendFileToDrive(allFiles[i]);}}}函数发送文件到驱动(文件){var reader = new FileReader();reader.onload = 函数 (e) {var content = reader.result;console.log('发送中' + file.name);var currFolder = '某事';google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);}reader.readAsDataURL(文件);}函数更新进度条(idUpdate){console.log('收到:' + idUpdate);numUploads.done++;var porc = Math.ceil((numUploads.done/numUploads.total)*100);$("#progressbar").progressbar({value: porc });$(".progress-label").text(numUploads.done +'/'+ numUploads.total);如果(numUploads.done == numUploads.total){//上传完成();numUploads.done = 0;};}</脚本><脚本>功能文件上传(状态){document.getElementById('myForm').style.display = 'none';document.getElementById('output').innerHTML = status;}</脚本><风格>身体 {最大宽度:400px;填充:20px;边距:自动;}输入 {显示:内联块;宽度:100%;填充:5px 0px 5px 5px;边距底部:10px;-webkit-box-sizing:边框框;‌ -moz-box-sizing: 边框;box-sizing:边框框;}选择 {边距:5px 0px 15px 0px;}输入[类型=提交"] {宽度:自动!重要;显示:块!重要;}输入[类型=文件"] {填充:5px 0px 15px 0px !重要;}#进度条{宽度:100%;文本对齐:居中;溢出:隐藏;位置:相对;垂直对齐:中间;}.进度标签{向左飘浮;边距顶部:5px;字体粗细:粗体;文字阴影:1px 1px 0 #fff;宽度:100%;高度:100%;位置:绝对;垂直对齐:中间;}</风格></身体>

code.gs:

函数 doGet() {返回 HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME);}函数uploadFileToDrive(base64Data,文件名){尝试{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(文件名);var dropbox = "某事";//文件夹名称var 文件夹,文件夹 = DriveApp.getFoldersByName(dropbox);如果(文件夹.hasNext()){文件夹 = 文件夹.next();} 别的 {文件夹 = DriveApp.createFolder(dropbox);}var file = folder.createFile(ss);返回文件.getName();}捕捉(e){return '错误:' + e.toString();}}

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.

Code.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

<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>

解决方案

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.

form.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:

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

这篇关于使用 Google App 脚本将多个文件上传到 Google Drive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)