将已添加到Google云端硬盘的图片链接插入到Google表格中 [英] Inserting a Link of a Picture That Had been Added to Google Drive into a Google Sheet

查看:83
本文介绍了将已添加到Google云端硬盘的图片链接插入到Google表格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是已在此处解决的问题的第二部分:

This is a second part to the problem that had been resolved here: Insert Image Link from Google Drive into Google Sheets After Uploading an Image via Web App

我正在开发一个Web应用程序,用户可以在其中单击按钮来上传图片.此操作会将具有唯一文件夹和名称的图片上传到我的Google驱动器中的某个目录中.

I'm developing a web application where a user can upload a picture by clicking on a button. This action will upload pictures into a certain directory in my google drive with a unique folder and name.

现在,我正试图在照片上传时复制并粘贴该照片的google驱动器链接.

Now, I'm trying to copy and paste the google drive link of a picture any time it has been uploaded.

在@Tanaike的帮助下,当我在文件夹中预先分配了一部分文件夹名称(fn)和图片标题(i)时,就可以将url的链接从google drive传递到google sheet中. "Code.gs"中的getFileUrl(fn,i)函数.但是我得到这个"TypeError:无法调用未定义的方法" getFilesByName".每当我尝试传递用户输入的"fn"和"i"时,都会输出.

With the help of @Tanaike, I was able to get the link of the url from google drive into the google sheet when I pre-assign a part of the folder name (fn) and the picture title (i) within the getFileUrl(fn,i) function in "Code.gs". But I get this "TypeError: Cannot call method "getFilesByName" of undefined." output whenever I try to pass the user-input "fn" and "i".

page.html -这是用户上传图片的前端

page.html --This is the front end, where a user uploads the picture

  <html>
  <head> 
   <body>
   <form action="#" method="post" enctype="multipart/form-data">
   <div class="row">
     <div class="file-field input-field">
        <div class="waves-effect waves-light btn-small">
          <i class="material-icons right">insert_photo</i>
          <span>Import Picture</span>
          <input id="files" type="file" name="image">
        </div>

        <div class="file-path-wrapper">
            <input disabled selected type="text" class="file-path 
             validate" placeholder="Choose an image">
        </div>
     </div>
  </div>
  </form>

 <?!= include("page-js"); ?>

</div> <!-- CLOSE CONTAINER-->


 </body>
</html>

这是将相关信息放入数组的javascript的一部分,以后将用于在Google表格中添加一行

This is part of the javascript to put relevant info in an array, which will later be used to append a row in the google sheet

page-js.html

     <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/1.0.0/js/materialize.min.js"></script>    
     <script src="https://gumroad.com/js/gumroad.js"></script>

     document.getElementById("files").addEventListener("loadend",doStuff1);
      
   document.getElementById("addAnother").addEventListener("click",doStuff1);
     
     <script>
     
     function doStuff1(){
        
           num.picNum2=i;
           var personName=document.getElementById("fn").value;
           google.script.run.withSuccessHandler(doStuff2).getFileUrl("fn","i"); // Modified by Tanaike
   
            
           var userInfo ={};
           userInfo.firstName= document.getElementById("fn").value;
           userInfo.number=i;
          userInfo.fileUrl=fileId00;        
          num.picNum=i;
           i++;
     google.script.run.userClicked(userInfo);
       
        }
        
          // Added by Tanaike
          function doStuff2(fileId00) {
            var userInfo = {};
            userInfo.firstName = document.getElementById("fn").value;
            userInfo.number = i;
            userInfo.fileUrl = "https://docs.google.com/document/d/"+fileId00 +"/";
            i++;
            google.script.run.userClicked(userInfo);
          }
</script>

这是将图片文件上传到Google驱动器的javascript的一部分

This is part of the javascript to upload picture file into the Google drive

(仍是page-js.html的一部分)

var file, 
  reader = new FileReader();
  var today = new Date();
  var date = today.getFullYear()+'-'+(today.getMonth()+1)+'- '+today.getDate();

  reader.onloadend = function(e) {
    if (e.target.error != null) {
      showError("File " + file.name + " could not be read.");
      return;
    } else {
      google.script.run
        .withSuccessHandler(showSuccess)
   .uploadFileToGoogleDrive(e.target.result,num.picNum,date,$('input#fn')
   .val(),$('input#date').val());

    }
  };

   function showSuccess(e) {
    if (e === "OK") { 
      $('#forminner').hide();
      $('#success').show();
    } else {
      showError(e);
    }
  }


     function submitForm() {


    var files = $('#files')[0].files;

    if (files.length === 0) {
      showError("Please select a image to upload");
      return;
    }

    file = files[0];

    if (file.size > 1024 * 1024 * 5) {
      showError("The file size should be < 5 MB.");
      return;
    }

    showMessage("Uploading file..");

    reader.readAsDataURL(file);


  }

        function showError(e) {
    $('#progress').addClass('red-text').html(e);
  }

  function showMessage(e) {
    $('#progress').removeClass('red-text').html(e);
  }

 </script>

这部分获取数组"userInfo",并将内容附加到指定的Google工作表中的一行中.任何时候,我都单击前端的按钮,它将创建一个新行. 在这里,如果我在getFileUrl函数中手动设置fn和i值,并在指定目录下有相应的图片和文件夹,则可以在Google工作表中找到有效的链接.但是,如果我将参数保留为用户在Web应用程序中输入的变量,则会在工作表中的链接中遇到上述错误.

This part grabs the array "userInfo" and appends the content in a row within a designated google sheet. Any time, I click on the button in the front end, it creates a new row. This is where if I set fn and i values within the getFileUrl function manually and have a correponding picture and a folder under the designated directory, I get a valid link back in my google sheet. However, if I leave the argument as variables that the user input in the web app, I get the aforementioned error in my link within the sheet.

Code.gs

//google sheet web script

    var url="https://docs.google.com/spreadsheets/d/XXXXX";

   function getFileUrl(fn,i){

  try{
      var today0 = new Date();
       var date0 = today0.getFullYear()+'-'+(today0.getMonth()+1)+'-' 
       +today0.getDate();

      var dropbox0 = "OE Audit Pictures";
      var folder0,folders0 = DriveApp.getFoldersByName(dropbox0);

     while (folders0.hasNext())
       var folder0=folders0.next();

      var dropbox20=[date0,fn].join(" ");


      var folder20,folders20=folder0.getFoldersByName(dropbox20);
      while (folders20.hasNext())
         var folder20=folders20.next();


         var file0, files0= folder20.getFilesByName(i);
      while (files0.hasNext())
        var file0=files0.next();


        var fileId0=file0.getUrl();


       return fileId0;
          }  catch(f){
  return f.toString();
        }
    }


  function userClicked(userInfo){

     var ss= SpreadsheetApp.openByUrl(url);
     var ws=ss.getSheetByName("Data");
      ws.appendRow([userInfo.number,new Date(), 
         userInfo.firstName,userInfo.fileUrl]);

      }

   function include(filename){
      return HtmlService.createHtmlOutputFromFile(filename).getContent();  
    }


  function uploadFileToGoogleDrive(data, file, fn, date) {

    try {

    var dropbox = "OE Audit Pictures";
    var folder, folders = DriveApp.getFoldersByName(dropbox);

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


   var contentType = data.substring(5,data.indexOf(';')),
     bytes = 
       Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),

       blob=Utilities.newBlob(bytes, contentType, file)

       var dropbox2=[fn,date].join(" ");
       var folder2, folders2=folder.getFoldersByName(dropbox2)

       if (folders2.hasNext()){
           folder2=folders2.next().createFile(blob);
       } else {
          file = folder.createFolder([fn,date].join(" ")).createFile(blob);
        }
       return "OK";

       } catch (f) {
      return f.toString();
       }    
     }

推荐答案

正如@Jescanellas和@Tanaike所评论的那样,更好的方法是修复您的代码,从而编辑page-js.html中的doStuff2函数,如下所示:

As @Jescanellas and @Tanaike commented, the better approach is to fix your code editing the function doStuff2 in page-js.html as this:

function doStuff2(fileId00) {
            var userInfo = {};
            userInfo.firstName = document.getElementById("fn").value;
            userInfo.number = i;
            userInfo.fileUrl = "https://docs.google.com/document/d/"+fileId00 +"/";
            i++;
            google.script.run.userClicked(userInfo);
          }

关于您遇到的错误,您没有在whiles中使用方括号,这是导致错误的原因,因为仅在循环内while后面的第一行. Code.gs :

About the error you're getting, you're not using the brackets in the whiles, this is causing the errors because only takes the first line after the while inside the loop. Code.gs:

while (folders0.hasNext()) {
     var folder0=folders0.next();

     var dropbox20=[date0,fn].join(" ");


     var folder20,folders20=folder0.getFoldersByName(dropbox20);
     while (folders20.hasNext()) {
         var folder20=folders20.next();


         var file0, files0= folder20.getFilesByName(i);
        while (files0.hasNext()) {
        var file0=files0.next();


        var fileId0=file0.getUrl();


       return fileId0;
       }
   }
}

关于文件ID的问题,创建文件后即可轻松获得,因为这将返回一个File对象,您可以使用getId方法[1]从中获取ID:

Regarding your question about the file Id, you can get it easily after you create the file, because this will return you a File object from which you can get the ID using the getId method [1]:

file = folder.createFolder([fn,date].join(" ")).createFile(blob);
fileId = file.getId();

[1] https://developers.google.com/apps-脚本/参考/驱动器/文件

这篇关于将已添加到Google云端硬盘的图片链接插入到Google表格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆