使用Google Apps脚本上传照片 [英] Uploading photo using Google Apps Script

查看:66
本文介绍了使用Google Apps脚本上传照片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用App脚本和Google表格以

完整的应用脚本代码为此处

我只需要知道如何添加联系人照片,就可以将其上传到表单中,并保存在Google表格中(或通过Google表格中的链接保存在Google云端硬盘中)

我阅读了,但这是不同的比我想要的要好.

解决方案

我相信您的目标如下.

  • 您要添加用于将图像文件上传到当前Google Apps脚本项目的功能.

修改点:

  • 在这种情况下,
    • 请将<输入类型=文件"> 的标签添加到 Form.html .
    • 在当前阶段,使用V8运行时时,对于二进制数据,无法在Google Apps脚本端正确解析表单对象.参考因此,二进制数据(图像文件)作为字节数组发送到Google Apps脚本端.
    • 为此,需要在您的Google Apps脚本中修改 processForm 的功能.

当以上几点反映到您的脚本中时,它如下所示.

修改后的脚本:

HTML端: Form.html

请按如下所示修改 Form.html .

从:

 < button type ="submit"class ="btn btn-primary"> Submit</button>< input class ="btn btn-secondary"type ="reset"值=重置" 

至:

 < div><输入类型=文件"id ="file"名称=文件"accept =图片/png,图片/jpeg"</div< ;!-已添加->< button type =提交";class ="btn btn-primary"> Submit</button>< input class ="btn btn-secondary"type ="reset"值=重置" 

JavaScript端: JavaScript.html

请按如下所示修改 JavaScript.html .

从:

  function handleFormSubmit(formObject){google.script.run.withSuccessHandler(createTable).processForm(formObject);document.getElementById("myForm").reset();} 

至:

 //我在下面添加了功能.这是从https://gist.github.com/tanaikech/58d96c023468fc1922d67764251b25e0const parseValues =异步(e)=>Object.assign(...(等待Promise.all([... e] .map((obj)=>新的Promise(异步(res)=> {const temp = {[obj.name]:""};如果(obj.type =="radio"){如果(obj.checked === true){temp [obj.name] = obj.value;}} else if(obj.type ==文件"){const files = obj.files;temp [obj.name] =等待(异步(文件)=> {返回等待Promise.all([...文件] .map((文件)=>新的Promise((resolve,reject)=> {const fr = new FileReader();fr.onload =(f)=>解决({文件名:file.name,mimeType:file.type,字节:[... new Int8Array(f.target.result)],});fr.onerror =(错误)=>拒绝(错误);fr.readAsArrayBuffer(file);})));})(文件).catch((err)=> console.log(err));} 别的 {temp [obj.name] = obj.value;}res(temp);})))));异步函数handleFormSubmit(formObject){//已修改var obj =等待parseValues(formObject);//添加google.script.run.withSuccessHandler(createTable).processForm(obj);//修改的document.getElementById("myForm").reset();} 

Google Apps脚本方面: Code.gs

从:

 函数processForm(formObject){if(formObject.RecId&& checkID(formObject.RecId)){//如果表单传递了ID,并且如果是现有ID,则执行updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId));//更新数据} else {//如果表单未传递ID,则执行appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange);//附加表格数据}return getLastTenRows();//返回最后10行} 

至:

 //我在下面添加了功能.函数saveFileToDrive(e){var blob = Utilities.newBlob(e.bytes,e.mimeType,e.filename);var file = DriveApp.getFolderById("root").createFile(blob);//在这种情况下,图像将保存到根文件夹中.请修改`root`为您的实际文件夹ID.返回file.getDownloadUrl();}函数processForm(formObject){var fileLink = formObject.file.length>0?saveFileToDrive(formObject.file [0]):";//添加if(formObject.RecId&& checkID(formObject.RecId)){//如果表单传递了ID,并且如果是现有ID,则执行updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId));//更新数据} else {//如果表单未传递ID,则执行appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange);//附加表格数据}return getLastTenRows();//返回最后10行} 

  • 当上述修改反映到您的Google Apps脚本项目中时,当您打开Web Apps时,您可以看到文件输入标签.选择图像文件并单击按钮时,将通过 parseValues()函数对表单对象进行解析,并将解析后的对象发送到Google Apps脚本端.在Google Apps脚本端,上传图片文件后,图片数据会作为文件保存到Google云端硬盘,下载链接会以 fileLink 返回.
  • 关于 fileLink 的值,请通过修改脚本将其用于您的实际情况.

注意:

  • 从您的脚本看来,您正在使用Web Apps.因此,当您修改脚本时,请重新部署Web Apps作为新版本.这样,最新脚本将反映到Web应用程序中.请注意这一点.
  • 这是一个简单的修改.因此,请根据您的实际情况修改HTML的样式以及用于放置到Google Spreadsheet中的值.
  • 在您提出问题的请求中,您说我只需要知道如何添加联系人照片,就可以将其上传到表单中,并保存在Google表格中(或带有链接的Google云端硬盘中)在Google表格中).
    • 关于此,当将图像作为Blob放置到Spreadsheet上时,再次从Spreadsheet检索图像有点麻烦.因此,在我的回答中,我建议通过将图像数据另存为Google云端硬盘中的文件来检索文件链接.

参考文献:

I want to build contact data using App Scripts and Google Sheets as here

Full App Script code is here

I just need to know how can I add the contact PHOTO, so it is getting uploaded in the form, and saved in the Google Sheets (or at Google Drive with link in the Google Sheets)

I read this but it is different than what I want.

解决方案

I believe your goal as follows.

  • You want to add the function for uploading an image file to your current Google Apps Script project.

Modification points:

  • In this case,
    • Please add a tag of <input type="file"> to Form.html.
    • In the current stage, when V8 runtime is used, in the case of the binary data, the form object cannot be correctly parsed at Google Apps Script side. Ref So, the binary data (image file) is sent to Google Apps Script side as the byte array.
    • By this, it is required to modify the function of processForm in your Google Apps Script.

When above points are reflected to your script, it becomes as follows.

Modified script:

HTML side: Form.html

Please modify Form.html as follows.

From:

<button type="submit" class="btn btn-primary">Submit</button>
<input class="btn btn-secondary" type="reset" value="Reset">

To:

<div><input type="file" id="file" name="file" accept="image/png,image/jpeg"></div>  <!-- Added -->

<button type="submit" class="btn btn-primary">Submit</button>
<input class="btn btn-secondary" type="reset" value="Reset">

Javascript side: JavaScript.html

Please modify JavaScript.html as follows.

From:

function handleFormSubmit(formObject) {
  google.script.run.withSuccessHandler(createTable).processForm(formObject);
  document.getElementById("myForm").reset();
}

To:

// I added below function. This is from https://gist.github.com/tanaikech/58d96c023468fc1922d67764251b25e0
const parseValues = async (e) =>
  Object.assign(
    ...(await Promise.all(
      [...e].map(
        (obj) =>
          new Promise(async (res) => {
            const temp = {[obj.name]: ""};
            if (obj.type == "radio") {
              if (obj.checked === true) {
                temp[obj.name] = obj.value;
              }
            } else if (obj.type == "file") {
              const files = obj.files;
              temp[obj.name] = await (async (files) => {
                return await Promise.all(
                  [...files].map(
                    (file) =>
                      new Promise((resolve, reject) => {
                        const fr = new FileReader();
                        fr.onload = (f) =>
                          resolve({
                            filename: file.name,
                            mimeType: file.type,
                            bytes: [...new Int8Array(f.target.result)],
                          });
                        fr.onerror = (err) => reject(err);
                        fr.readAsArrayBuffer(file);
                      })
                  )
                );
              })(files).catch((err) => console.log(err));
            } else {
              temp[obj.name] = obj.value;
            }
            res(temp);
          })
      )
    ))
  );

async function handleFormSubmit(formObject) {  // Modified
  var obj = await parseValues(formObject);  // Added
  google.script.run.withSuccessHandler(createTable).processForm(obj);  // Modified
  document.getElementById("myForm").reset();
}

Google Apps Script side: Code.gs

From:

function processForm(formObject){  
  if(formObject.RecId && checkID(formObject.RecId)){//Execute if form passes an ID and if is an existing ID
    updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId)); // Update Data
  }else{ //Execute if form does not pass an ID
    appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange); //Append Form Data
  }
  return getLastTenRows();//Return last 10 rows
}

To:

// I added below function.
function saveFileToDrive(e) {
  var blob = Utilities.newBlob(e.bytes, e.mimeType, e.filename);
  var file = DriveApp.getFolderById("root").createFile(blob);  // In this case, the image is saved to the root folder. Please modify `root` to your actulal folder ID.
  return file.getDownloadUrl();
}

function processForm(formObject){

  var fileLink = formObject.file.length > 0 ? saveFileToDrive(formObject.file[0]) : "";  // Added

  if(formObject.RecId && checkID(formObject.RecId)){//Execute if form passes an ID and if is an existing ID
    updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId)); // Update Data
  }else{ //Execute if form does not pass an ID
    appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange); //Append Form Data
  }
  return getLastTenRows();//Return last 10 rows
}

  • When above modification is reflected to your Google Apps Script project, when you opened the Web Apps, you can see the file input tag. When you selected an image file and click the button, the form object is parsed by a function of parseValues(), and the parsed object is sent to Google Apps Script side. At Google Apps Script side, when the image file is uploaded, the image data is saved as a file to Google Drive and the download link is returned as fileLink.
  • About the value of fileLink, please use it for your actual situation by modifying the script.

Note:

  • From your script, it seems that you are using Web Apps. So, when you modified the script, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
  • This is a simple modification. So please modify the style of HTML and the values for putting to Google Spreadsheet for your actual situation.
  • In your request in your question, you say I just need to know how can I add the contact PHOTO, so it is getting uploaded in the form, and saved in the Google Sheets (or at Google Drive with link in the Google Sheets).
    • About this, when the image is put to the Spreadsheet as a blob, it is a bit complecate for retrieving the image from Spreadsheet again. So in my answer, I proposed to retrieve the file link by saving the image data as a file on Google Drive.

References:

这篇关于使用Google Apps脚本上传照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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