2

这是我第一次使用js和html编码的方法,请尽可能简单!

我想改进在我的网络应用程序中开发的表单,使上传图像成为可能。我的目标是:

  • 在我的网络应用程序上添加输入类型文件
  • 将文件发送到服务器端
  • 将文件保存在 G Drive 中,获取链接并将其保存在 Google Sheet 中

为此,我已经在我的 html 中添加了一个文件输入区域,但我不确定如何在脚本部分管理它。

表单中添加的所有信息都在一个名为的对象中发送到服务器,measureInfo我想维护这个例程。当我尝试添加

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

它没有运行并且控制台返回`由于属性中的非法值而失败:媒体。

在这里我报告一些可能有助于回答的代码字符串。如果您对如何使用 DriveApp 在服务器端管理文件有一些建议,请分享!

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

3 回答 3

1

您可以使用FileReader.onload事件来构建可以在服务器端传递的对象:

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

参考:

于 2020-06-18T12:33:32.903 回答
0

这是我用来保存收据的一些代码:

带有 JS 的 HTML:

<!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};
}
于 2020-06-16T15:16:32.953 回答
0
<script>
   function preventFormSubmit(){
     var forms=document.querySelectorAll('form');
     for (var i=0;i<forms.length;i++){
       forms[i].addEventListener('submit',function(event){
         event.preventDefault();
       });
     }
   }
   window.addEventListener('load',preventFormSubmit);
   
   function handleFormSubmit(formObject){
   google.script.run.processForm(formObject);
   document.getElementById("myForm").reset();
   }
   
</script>
<script>
   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};
   }
</script>
<!DOCTYPE html>
<html lang="en">
   <head>
      <base target="_top">
      <?!= include('JavaScript'); ?>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      <head>
         <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>
         </head
   <body>
      <div class="form-row">
      <div class="form-group col-md-12">
      <h5 style="text-align:center;">Upload Photo</h5>
      <div class="form-row">
      <div class="form-group col-md-4" style="word-wrap: break-word">
         <p3 style="text-align:left; color:red">
         Notice! Please doff eyewear & mask and avoid sunlight exposure when taking selfie!</p>
      </div>
      <div class="form-group col-md-6"><img id="output" width="200" height="200" src="https://www.citypng.com/public/uploads/small/116395943260tji5ordfujy44njydzhlidv8reqpmtun7ggx1oszpz1dcistzxnmag7do6vxkjxphlsgueuurkg9pkpbwgorvv9lratpxm38rp5.png"  alt="photo" style="border:gray; border-width:2px; border-style:solid;"/></div>
      <div class="form-group col-md-12">
         <center>
         &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp;<input class="file-path validate" type="file" id="fileUpload" name="fileUpload" value='fileUpload'  accept="image/*" onchange="loadFile(event)">
         <script>
            var loadFile = function(event) {
              var output = document.getElementById('output');
              output.src = URL.createObjectURL(event.target.files[0]);
              output.onload = function() {
                URL.revokeObjectURL(output.src) // free memory
              }
            };
         </script>
      </div>
   </body>
</html>


  [1]: https://i.stack.imgur.com/98vPf.png
于 2022-03-04T09:17:23.943 回答