简体   繁体   中英

Upload image into Google Drive via Web App and save correspondent link on spreadsheet

This is my first approach with js and html coding, please be as much simple as possible!

I want to improve the form developed in my web App making possible to upload image. My goal is to:

  • Add input type file on my web App
  • Send the file to server side
  • Save the file in the G Drive, take the link and save it in Google Sheet

To do this I have already added in my html a file input area, but I'm not sure about how I may manage it in script section.

All the information added in the form are send to server in an object called measureInfo and I want to maintain this routine. When I try to add

measureInfo.media = document.getElementById('fileUpload').files

it doesn't run and console return `Failed due to illegal value in property: media.

Here I report some string of code that may help to answer. If you have some suggests about how manage file in server side with DriveApp please share!

   <script>
            measureInfo.media= document.getElementById('fileUpload').files

            google.script.run.sendToDatabase(measureInfo);
</script>
<form action="#">
    <!-- Upload File -->
    <div class="file-field input-field">
        <div class="btn-large blue darken-3">
            <span>Media</span>
            <input type="file" id= 'fileUpload' name ='fileUpload'>
        </div>
        <div class="file-path-wrapper">
            <input class="file-path validate" type="text" placeholder = 'Upload Media'>
        </div>
    </div>
</form>

You could use FileReader.onload event to build an object that can be passed server-side:

const file = document.getElementById('fileUpload').files[0];
const fr = new FileReader();
fr.onload = (e) => {
  const data = e.target.result.split(",");
  measureInfo.media = {fileName: file.name, mimeType: file.type, data: data[1]};       
  google.script.run.sendToDatabase(measureInfo);
}
fr.readAsDataURL(file);

Reference:

Here's some code I use for saving receipts:

HTML with JS:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
      $(function(){
        google.script.run
        .withSuccessHandler(function(rObj){
          $('#dt').val(rObj.date);
        })
        .initForm();

      });
      function fileUploadJs(frmData) {
        var amt=$('#amt').val();
        var vndr=$('#vndr').val();
        var img=$('#img').val();
        if(!amt){
          window.alert('No amount provided');
          $('#amt').focus();
          return;
        }
        if(!vndr) {
          window.alert('No vendor provided');
          $('#vndr').focus();
          return;
        }
        if(!img) {
          window.alert('No image chosen');
          $('#img').focus();
        }
        document.getElementById('status').style.display ='inline';
        google.script.run
        .withSuccessHandler(function(hl){
          document.getElementById('status').innerHTML=hl;
        })
        .uploadTheForm(frmData)
      }
      console.log('My Code');
    </script>
    <style>
      input,textarea{margin:5px 5px 5px 0;}
    </style>
  </head>
   <body>
    <h3 id="main-heading">Receipt Information</h3>
    <div id="formDiv">
      <form id="myForm">
        <br /><input type="date" name="date" id="dt"/>
        <br /><input type="number" name="amount" placeholder="Amount" id="amt" />
        <br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
        <br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
        <br/>Receipt Image
        <br /><input type="file" name="receipt" id="img" />
        <br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
      </form>
    </div>
  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
  </div>  
</body>
</html>

GS:

function uploadTheForm(theForm) {
  var rObj={};
  rObj['vendor']=theForm.vendor;
  rObj['amount']=theForm.amount;
  rObj['date']=theForm.date;
  rObj['notes']=theForm.notes
  var fileBlob=theForm.receipt;
  var fldr = DriveApp.getFolderById(receiptImageFolderId);
  rObj['file']=fldr.createFile(fileBlob);
  rObj['filetype']=fileBlob.getContentType(); 
  Logger.log(JSON.stringify(rObj));
  var cObj=formatFileName(rObj);
  Logger.log(JSON.stringify(cObj));
  var ss=SpreadsheetApp.openById(SSID);
  ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
  var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
  return html;
}

function formatFileName(rObj) {
  if(rObj) {
    Logger.log(JSON.stringify(rObj));
    var mA=rObj.date.split('-');
    var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
    rObj.file.setName(name);
  }else{
      throw('Invalid or No File in formatFileName() upload.gs');
  }
  return rObj;
}

function initForm() {
  var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
  return {date:datestring};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM