首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将文件上传blob从HTML表单传递到服务器端应用程序脚本?

如何将文件上传blob从HTML表单传递到服务器端应用程序脚本?
EN

Stack Overflow用户
提问于 2019-08-20 15:57:40
回答 2查看 1.9K关注 0票数 0

表单标题下的Google 支持文章示例已中断。从该条中:

如果以表单元素作为参数调用服务器函数,表单将成为一个单独的对象,字段名作为键,字段值作为值。这些值都被转换成字符串,除了文件输入字段的内容,这些字段成为Blob对象。

我通过传递一个包含5个文本输入和一个文件的表单元素,然后在Form对象上记录Object.keys()来测试这一点。它只返回5个文本字段,该文件被从form对象中剥离。试图分配直接返回的Exception: Invalid argument: blob文件blob

如何将文件blob从客户端表单传递给服务器端应用程序脚本?

编辑:为了澄清,我还复制粘贴了Google逐字提供的示例。它与Exception: Invalid argument: blob错误。

复制:

  1. 创建新的Google脚本项目
  2. Index.html内容:
代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      // Prevent forms from submitting.
      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.withSuccessHandler(updateUrl).processForm(formObject);
      }
      function updateUrl(url) {
        var div = document.getElementById('output');
        div.innerHTML = '<a href="' + url + '">Got it!</a>';
      }
    </script>
  </head>
  <body>
    <form id="myForm" onsubmit="handleFormSubmit(this)">
      <input name="myFile" type="file" />
      <input type="submit" value="Submit" />
    </form>
    <div id="output"></div>
 </body>
</html>
  1. Code.gs内容:
代码语言:javascript
运行
复制
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function processForm(formObject) {
  var formBlob = formObject.myFile;
  var driveFile = DriveApp.createFile(formBlob);
  return driveFile.getUrl();
}
  1. 发布为Web应用程序
  2. 提交带有任何文件的表单
  3. 观察视图->堆栈驱动程序日志->应用程序脚本仪表板中的错误
EN

回答 2

Stack Overflow用户

发布于 2019-08-20 21:06:59

下面是一个例子:

html:

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
  <head>
  <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 fileUploadJs(frmData) {
    document.getElementById('status').style.display ='inline';
    google.script.run
      .withSuccessHandler(updateOutput)
      .uploadTheFile(frmData)
  }

  function updateOutput(info)  {
    var br='<br />';
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = br + 'File Upload Successful.' + br + 'File Name: ' + info.name + br + 'Content Type: ' + info.type + br + 'Folder Name: ' + info.folder;
  }

  console.log('My Code');
</script>
<style>
  body {background-color:#ffffff;}
  input{padding:2px;margin:2px;}
</style>

  </head>
  <body>
    <h1 id="main-heading">Walking Tracks</h1>
    <h3>Upload GPS Tracks Files</h3>
    <div id="formDiv">
      <form id="myForm">
        <input name="fileToLoad" type="file" /><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>  
  <div id="controls">
      <input type="button" value="Close" onClick="google.script.host.close();" />
  </div>
</body>
</html>

服务器代码:

代码语言:javascript
运行
复制
function uploadTheFile(theForm) {
  var fileBlob=theForm.fileToLoad;
  var fldr = DriveApp.getFolderById('FolderId');
  var file=fldr.createFile(fileBlob);
  var fi=formatFileName(file);
  var fileInfo={'name':fi.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName()};
  return fileInfo;
}
票数 1
EN

Stack Overflow用户

发布于 2019-09-17 13:18:33

我可以确认这在G-Suite Enterprise中行不通。我不知道为什么,因为我找不到说明Google如何序列化数据的文档。它可能是浏览器/计算机安全设置或G-Suite中的什么东西。

然而,有一个更容易的方式来满足您的需要。您可以使用带有文件上传问题的Google,然后在其上创建一个on form submit触发器/事件,将文件复制到团队/共享驱动器中。如果您想将触发器附加到Google表单本身,下面是示例代码:

代码语言:javascript
运行
复制
// ID of the destnation folder to save the file in
var destinationFolderID = "10gkU_2V9iYy-VKudOCOjydEpoepPTgPv"

function saveFileToTeamDrive(e)
{
  // a place to save the URL of the uploaded file
  var fileID;

  // go through all of the responses to find the URL of the uploaded file
  e.response.getItemResponses().forEach(function(itemResponse){
    // once we find the question with the file
    if(itemResponse.getItem().getTitle() == "File Upload Test")
    {
      // get the file ID from the response
      fileID = itemResponse.getResponse();
      return;
    }
  });

  // stop if we didn't have one
  if(!fileID.length) return;

  // get the first index in the array
  fileID = fileID[0];

  // get the file
  var file = DriveApp.getFileById(fileID);

  // get the destination folder
  var destinationFolder = DriveApp.getFolderById(destinationFolderID);

  // make a copy
  var newFile = file.makeCopy(destinationFolder);

  Logger.log(newFile.getUrl());
}

您还可以附加到链接到Google表单的Google工作表的on form submit事件。我发现这种方法更容易,因为Google on form submit触发器/事件包含一个问题/答案的JSON,所以您不必迭代所有它们才能找到它。这也意味着如果提交失败,您可以重新运行它。

警告

一个重要的注意事项是,如果您这样做,请不要让其他任何人编辑代码。这是因为一旦您创建并授权了触发器,任何对代码进行编辑访问的人都可以使用它来访问您的Google (以及触发器授权的任何其他内容)。有关更多信息,请参见保护链接到授权触发器的Google脚本,以便其他人可以编辑

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57577487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档