使用 Google Apps 脚本直接将文件上传到我的 Google 云端硬盘(不使用 Google 表单)
P粉785905797
P粉785905797 2024-01-21 15:39:43
0
2
501

所以基本上任务非常简单,但我没有找到任何可行的解决方案来解决我的问题。我的网站上有一个巨大的上传脚本(目前是本地主机),但让我们将所有复杂性减少到唯一必要的程度。

所以我只想使用 Google App Script 将单个文件上传到 Google 云端硬盘,并接收它的 URL 以将其保存在 var 中,以便稍后在我的函数中使用该信息。

现在的问题是我的网站上已经有该表单,我不希望 script.google .com 内的表单作为额外的 html,我想将我的用户输入传输到 Google App Script,然后将其上传到 google 驱动器并将 url 返回到我的网站,我可以将其保存到 var 中。

我现在的问题是,我无法将所有的东西放在一起。

这是我网站上的表格(简化):

<form name="myForm" method="post">
            <!-- <form name="first-form"> -->

  <input type="text" placeholder="Name" id="myName">
  <input type="file" name="myFile" id="myFile">
  <button onclick="UploadFile()" type="submit">submit</button>

</form>

那么我如何在 Google Drive 中上传我的信息并获取结果呢?如何在不使用 iFrame 或其他任何东西的情况下推送 Google App 脚本中的数据?

谢谢!

**** 如果 html 位于 script.google .com 中,则工作示例 ****

GS

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('forms.html').setTitle("Google File Upload by CTRLQ.org");
}


function uploadFileToGoogleDrive(data, file, name, email) {
  
  try {
    
    var dropbox = "Received Files";
    var folder, folders = DriveApp.getFoldersByName(dropbox);
    
    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    
    /* Credit: www.labnol.org/awesome */
    
    var contentType = data.substring(5,data.indexOf(';')),
        bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
        blob = Utilities.newBlob(bytes, contentType, file),
        file = folder.createFolder([name, email].join(" ")).createFile(blob);
    
    return "OK";
    
  } catch (f) {
    return f.toString();
  }
  
}

apps.googlescript 中的 html

<!DOCTYPE html>
<html>
  <head>
    <base target="_blank">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Google File Upload by CTRLQ.org</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
    <style>
      .disclaimer{width: 480px; color:#646464;margin:20px auto;padding:0 16px;text-align:center;font:400 12px Roboto,Helvetica,Arial,sans-serif}.disclaimer a{color:#009688}#credit{display:none}
    </style>
  </head>
  <body>

    <!-- Written by Amit Agarwal amit@labnol.org --> 

    <form class="main" id="form" novalidate="novalidate" style="max-width: 480px;margin: 40px auto;">
      <div id="forminner">
        <div class="row">
          <div class="col s12">
            <h5 class="center-align teal-text">Upload Files to my Google Drive</h5>
            <p class="disclaimer">This <a href="http://www.labnol.org/internet/file-upload-google-forms/29170/">File Upload Form</a> (<a href="https://youtu.be/C_YBBupebvE">tutorial</a>) is powered by <a href="https://ctrlq.org/code/19747-google-forms-upload-files" target="_blank">Google Scripts</a></p>
          </div>
        </div>
        <div class="row">
          <div class="input-field col s12">
            <input id="name" type="text" name="Name" class="validate" required="" aria-required="true">
            <label for="name">Name</label>
          </div>
        </div>
        <div class="row">
          <div class="input-field col s12">
            <input id="email" type="email" name="Email" class="validate" required="" aria-required="true">
            <label for="email">Email Address</label>
          </div>
        </div>

        <div class="row">
          <div class="file-field input-field col s12">
            <div class="btn">
              <span>File</span>
              <input id="files" type="file">
            </div>
            <div class="file-path-wrapper">
              <input class="file-path validate" type="text" placeholder="Select a file on your computer">
            </div>
          </div>
        </div>

        <div class="row">
          <div class="input-field col s6">
            <button class="waves-effect waves-light btn submit-btn" type="submit" onclick="submitForm(); return false;">Submit</button>
          </div>   
        </div>
        <div class="row">
          <div class="input-field col s12" id = "progress">
          </div>
        </div>
      </div>
      <div id="success" style="display:none">
        <h5 class="left-align teal-text">File Uploaded</h5>
        <p>Your file has been successfully uploaded.</p>
        <p>The <a href="http://www.labnol.org/internet/file-upload-google-forms/29170/">pro version</a> (see <a href="">demo form</a>) includes a visual drag-n-drop form builder, CAPTCHAs, the form responses are saved in a Google Spreadsheet and respondents can upload multiple files of any size.</p>    
        <p class="center-align"><a  class="btn btn-large" href="https://gum.co/GA14?wanted=true" target="_blank">Upgrade to Pro</a></p>
      </div>
    </form>

    <div class="fixed-action-btn horizontal" style="bottom: 45px; right: 24px;">
      <a class="btn-floating btn-large red">
        <i class="large material-icons">menu</i>
      </a>
      <ul>
        <li><a class="btn-floating red"  href="https://gum.co/GA14" target="_blank" title="Buy License - File Upload Form"><i class="material-icons">monetization_on</i></a></li>
        <li><a class="btn-floating blue"  href="https://youtu.be/C_YBBupebvE" target="_blank" title="Video Tutorial"><i class="material-icons">video_library</i></a></li>
        <li><a class="btn-floating green" href="http://www.labnol.org/internet/file-upload-google-forms/29170/" target="_blank" title="How to Create File Upload Forms"><i class="material-icons">help</i></a></li>
      </ul>
    </div>

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

    <script>

      var file, 
          reader = new FileReader();

      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, file.name, $('input#name').val(), $('input#email').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 file to upload");
          return;
        }

        file = files[0];

        if (file.size > 1024 * 1024 * 5) {
          showError("The file size should be < 5 MB. Please <a href='http://www.labnol.org/internet/file-upload-google-forms/29170/' target='_blank'>upgrade to premium</a> for receiving larger files in Google Drive");
          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>

  </body>

</html>

按照建议,我将在这里描述该过程。

所以我们在网站上:www.example.com,有一个带有文本输入字段和文件字段的表单。假设我们放入一张图像并将其称为示例。现在,如果我们按提交,我想将图像上传到谷歌驱动器,而不需要任何oAuth(这就是为什么我们需要在此处使用谷歌应用程序脚本)并将其命名为我们在文本字段中键入的内容。上传完成后,我希望将 google Drive 图像的 url 返回到网站,以便表单可以继续使用该信息。我想将返回的 url 保存在 var 中,稍后将其保存在数据库中。这就是为什么我需要将结果返回到我的网站。

因此方案如下所示:

在网站上输入信息到表单 -> 重定向到 google 应用程序脚本:获取网站表单字段的信息并将文件上传到 google 驱动器,并将其命名为文本输入条目 -> 将 google 驱动器的 url 作为最终结果 -> 重定向最终url 结果返回网站 -> 将 url 结果保存在 var 中并继续从网站 -> 上的函数执行操作,最后将 var 中的信息保存到数据库 -> finish

------------------------------------------------------------ - 编辑: ------------------

感谢@Tanaike,我离我的挑战目标更近了,所以为了看看我陷入了困境,我现在正在复制我的问题:

我使用您示例中的脚本获取了表单:

<form id="form">
  <input name="file" id="uploadfile" type="file">
  <input name="filename" id="filename" type="text">
  <input id="submit" type="submit">
</form>
<script>
const form = document.getElementById('form');
form.addEventLis tener('submit', e => {
  e.preventDefault();
  const file = form.file.files[0];
  const fr = new FileReader();
  fr.readAsArrayBuffer(file);
  fr.onload = f => {
    
    const url = "https://script.google .com/macros/s/###/exec";  // <--- Please set the URL of Web Apps.
    
    const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
    fetch(`${url}?${qs}`, {method: "POST", body: JSON.stringify([...new Int8Array(f.target.result)])})
    .then(res => res.json())
    .then(e => console.log(e))  // <--- You can retrieve the returned value here.
    .catch(err => console.log(err));
  }
});
</script>

对于谷歌脚本:

function doPost(e) {
  // const folderId = "###";  // Folder ID which is used for putting the file, if you need.

  const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);
  const file = DriveApp.getFolderById(folderId || "root").createFile(blob);
  const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};
  return ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);
}

现在,当我尝试上传某些内容时,出现以下错误:CORS 策略无法获取。所以我将这部分更改为以下内容并添加了 no cors 模式:

const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
        fetch(`${url}?${qs}`, {method: "POST", mode: "no-cors", body: JSON.stringify([...new Int8Array(f.target.result)])})

这有效。第二次尝试上传文件导致以下错误: 它说:syntax错误:输入意外结束

所以我更改了这一行并从 res.json 中删除了括号

JSON.stringify([...new Int8Array(f.target.result)])})
        .then(res => res.json)

第三次尝试上传实际有效的文件,控制台结果如下:

ƒ json() { [native code] }

但是 Google 云端硬盘中没有上传文件。我在某个地方缺少一些东西。也许我们应该创建一个文件夹并将文件放入其中。

哦,还有另一个信息:当我在 google app sript 中运行 doPost 函数时,它说:

TypeError: Cannot read property 'postData' of undefined (line 13

编辑2 -----------------------------------------------------

我将 https://drive.google .com/uc?export=download&id=

fileId

添加到您的代码中,一切正常。文件正在上传。

假设我们上传文件 test.mp3,并将其命名为 testdata。 这是我们收到的:

{
  "filename": "testdata",
  "fileId": "###some id##",
  "fileUrl": "https://drive.google .com/uc?export=download&id=###fileId###"
}

现在,当我打开文件 url 时,浏览器会下载文件,但其名称为:testdata,而不是 testdata.mp3。文件类型结尾丢失。

第二个任务:如果您单击链接,我想在浏览器中打开该文件,例如,当它是 mp3 文件时,我希望您可以在 webview 中播放声音,就像这里一样:https://files.freemusicarchive .org/storage-freemusicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Decalo.mp3

希望您能指导我!######
P粉785905797
P粉785905797

全部回复(2)
P粉512729862

https://stackoverflow.com/a/63391363/1585523 答案中有很多有用的提示!感谢你的分享。除了 POST 文件之外,我们还可以使用

在客户端:index.html

google.script.run.withSuccessHandler(fileName => {}).withFailureHandler(error => {}).saveInDrive(fileAsByteArray);

在服务器上:Code.gs

function saveInDrive(f) {
  const blob = Utilities.newBlob(f, "image/jpeg", "some-name");
  const file = DriveApp.getFolderById("root").createFile(blob);
  return file.getName()
}

您甚至可以用这种方法交换复杂类型,例如 JS 对象与二进制信息作为值。

P粉298305266

我相信您的目标如下。

  • 您的网站与 Google 帐户无关。它是独立的。
  • 您的网站有一个用于上传文件的表单。
  • 当用户提交表单时,您希望在未经授权的情况下将文件上传到您的 Google 云端硬盘,并希望返回已上传文件在 Google 云端硬盘上的网址。
  • 关于“数据库”,这是您的数据库。您将检索到的文件 URL 放入客户端的“数据库”中。

在这种情况下,我认为使用 Google Apps 脚本创建的网络应用程序可以实现您的目标。

用法:

请执行以下流程。

1。创建 Google Apps 脚本的新项目。

Web Apps 的示例脚本是 Google Apps 脚本。因此,请创建一个 Google Apps 脚本项目。

如果您想直接创建,请访问https://script.new/。在这种情况下,如果您尚未登录 Google,则会打开登录屏幕。所以请登录谷歌。这样,Google Apps 脚本的脚本编辑器就会打开。

2。准备脚本。

请将以下脚本(Google Apps 脚本)复制并粘贴到脚本编辑器中。该脚本适用于网络应用程序。

服务器端:Google Apps 脚本

请设置要放置文件的文件夹ID。

function doPost(e) {
  const folderId = "root";  // Or Folder ID which is used for putting the file instead of "root", if you need.

  const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);
  const file = DriveApp.getFolderById(folderId).createFile(blob);
  const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};
  return ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);
}

3。部署网络应用程序。

  1. 在脚本编辑器中,通过“发布”->“部署为网络应用”打开一个对话框。
  2. “执行应用程序:”选择“我”
    • 这样,脚本就会以所有者的身份运行。
  3. “谁有权访问该应用:”选择“任何人,甚至匿名”
  4. 点击“部署”按钮作为新的“项目版本”。
  5. 自动打开“需要授权”对话框。
    1. 点击“查看权限”。
    2. 选择自己的帐户。
    3. 点击“此应用未经验证”处的“高级”。
    4. 点击“转到
    5. 项目名称
    6. (不安全)”
    点击“允许”按钮。
  6. 点击“确定”。 复制网络应用程序的 URL。就像
      https://script.google.com/macros/s/
    • /exec
    修改 Google Apps 脚本后,请重新部署为新版本。这样,修改后的脚本就会反映到Web Apps中。请小心这一点。

4。从客户端上传文件到服务器端。

客户端:HTML 和 Javascript
  • 请将您的 Web 应用程序的 URL 设置为以下脚本。
sssccc

在客户端,当您从本地 PC 选择文件并按下按钮时,系统会通过在网络应用(服务器端)检索数据来将该文件上传到您的 Google 云端硬盘。

结果:### ###运行上述脚本时,将返回以下值。由此,您可以检索文件的 URL。###
{
  "filename": "### inputted filename ###",
  "fileId": "###",
  "fileUrl": "https://drive.google.com/file/d/###/view?usp=drivesdk"
}

注意:

  • 当您修改Web Apps的脚本时,请将Web Apps重新部署为新版本。这样,最新的脚本就会反映到Web Apps中。请小心这一点。
  • 在上面的脚本中,最大文件大小为 50 MB。因为在当前阶段,Google Apps 脚本的最大 blob 大小为 50 MB。

参考文献:

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!