使用 Google Apps 脚本将文件上传到我的谷歌驱动器(GOOGLE 中没有表格) [英] Upload file to my google drive with Google Apps Script (NO FORM IN GOOGLE)

查看:44
本文介绍了使用 Google Apps 脚本将文件上传到我的谷歌驱动器(GOOGLE 中没有表格)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

所以我只想使用 Google App Script 将单个文件上传到 Google Drive 并接收它的 URL 以将其保存在一个 var 中,以便在我的函数中稍后处理该信息.

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

我现在的问题是,我不能把所有的东西放在一起.

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

<!-- <表单名称=第一表单">--><输入类型=文本"占位符=名称"id=我的名字"><输入类型=文件"名称=我的文件"id=我的文件">

那么如何将我的信息上传到谷歌驱动器中并获取结果?如何在不使用 iFrame 或其他任何东西的情况下在 Google App Script 中推送数据?

谢谢!

**** 如果 html 在 scripts.google.com 中的工作示例 ****

gs

function doGet(e) {return HtmlService.createHtmlOutputFromFile('forms.html').setTitle("Google File Upload by CTRLQ.org");}功能uploadFileToGoogleDrive(数据,文件,名称,电子邮件){尝试 {var dropbox =接收的文件";var 文件夹,文件夹 = DriveApp.getFoldersByName(dropbox);如果(文件夹.hasNext()){文件夹 = folders.next();} 别的 {文件夹 = DriveApp.createFolder(dropbox);}/* 信用:www.labnol.org/awesome */var contentType = data.substring(5,data.indexOf(';')),字节 = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),blob = Utilities.newBlob(bytes, contentType, file),file = folder.createFolder([name, email].join(" ")).createFile(blob);返回OK";}赶上(f){返回 f.toString();}}

apps.googlescript 中的 html

<头><基本目标=_blank"><元名称=视口"内容=宽度=设备宽度,初始比例=1.0";/><title>由 CTRLQ.org 上传的 Google 文件</title><link rel="样式表";href=https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"><风格>.免责声明{宽度: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}</风格><身体><!-- 作者:Amit Agarwal amit@labnol.org --><form class="main"id=形式"novalidate=novalidate"style="max-width: 480px;margin: 40px auto;"><div id="forminner"><div class="row"><div class="col s12"><h5 class="center-align blue-text">将文件上传到我的 Google Drive</h5><p class="disclaimer">这个<a href="http://www.labnol.org/internet/file-upload-google-forms/29170/">文件上传表单</>(<a href="https://youtu.be/C_YBBupebvE">教程</a>)由<a href="https://ctrlq.org/code/19747-google-提供支持表单上传文件"target=_blank">Google Scripts</a></p>

<div class="row"><div class="input-field col s12"><label for="name">Name</label>

<div class="row"><div class="input-field col s12"><input id="email";类型=电子邮件"名称=电子邮件"类=验证"必需="aria-required="true"><label for="email">电子邮件地址</label>

<div class="row"><div class="file-field input-field col s12"><div class="btn"><span>文件</span><输入id=文件"类型=文件">

<div class="file-path-wrapper"><input class="file-path validate";类型=文本"placeholder="选择计算机上的文件">

<div class="row"><div class="input-field col s6"><button class="waves-effect wave-light btn submit-btn";类型=提交"onclick="submitForm();return false;">提交</button>

<div class="row"><div class="input-field col s12";id =进度">

<div id="成功";样式=显示:无"><h5 class="left-align blue-text">上传的文件</h5><p>您的文件已成功上传.</p><p><a href=http://www.labnol.org/internet/file-upload-google-forms/29170/">专业版</a>(参见<a href="">演示表单</a>)包括一个可视化拖放表单构建器,CAPTCHA,表单回复保存在谷歌电子表格中,受访者可以上传任何</p><p class="center-align"><a class="btn btn-large"href=https://gum.co/GA14?wanted=true"target=_blank">升级到Pro</a></p>

</表单><div class="fixed-action-btnhorizo​​ntal";样式=底部:45px;右: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"目标=_blank";title=购买许可 - 文件上传表单">monetization_on<li><a class="btn-floating blue";href=https://youtu.be/C_YBBupebvE"目标=_blank";title=视频教程"><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/";目标=_blank";title="如何创建文件上传表单"><i class="material-icons">help</i></a></li>

<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><脚本>var 文件,reader = new FileReader();reader.onloadend = 函数(e){如果(e.target.error != null){showError(文件"+文件名+无法读取.");返回;} 别的 {google.script.run.withSuccessHandler(showSuccess).uploadFileToGoogleDrive(e.target.result, file.name, $('input#name').val(), $('input#email').val());}};函数 showSuccess(e) {如果(e ===好"){$('#forminner').hide();$('#success').show();} 别的 {显示错误(e);}}函数提交表单(){var files = $('#files')[0].files;if (files.length === 0) {showError("请选择要上传的文件");返回;}文件 = 文件 [0];如果(文件大小> 1024 * 1024 * 5){showError("文件大小应该小于 5 MB.请<a href='http://www.labnol.org/internet/file-upload-google-forms/29170/' target='_blank'>升级到高级版</a>以在 Google Drive 中接收更大的文件");返回;}showMessage(上传文件..");reader.readAsDataURL(文件);}函数 showError(e) {$('#progress').addClass('red-text').html(e);}函数 showMessage(e) {$('#progress').removeClass('red-text').html(e);}</html>

作为推荐,我将在这里描述这个过程.

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

所以方案如下所示:

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

------------------------------------------------ ------------------

感谢@Tanaike,我更接近我在这里挑战的目标,所以为了看看我在哪里卡住了,我现在正在复制我的问题:

我从您的示例中获取了带有脚本的表单:

<输入名称=文件"id="上传文件"类型=文件"><输入名称=文件名"id=文件名"类型=文本"><输入id=提交";类型=提交"></表单><脚本>const form = document.getElementById('form');form.addEventListener('提交', e => {e.preventDefault();const file = form.file.files[0];const fr = new FileReader();fr.readAsArrayBuffer(文件);fr.onload = f =>{const url = "https://script.google.com/macros/s/###/exec";//<--- 请设置 Web 应用程序的 URL.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))//<--- 您可以在此处检索返回值..catch(err => console.log(err));}});

对于谷歌脚本:

function doPost(e) {//const folderId = "###";//如果需要,用于放置文件的文件夹 ID.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()};返回 ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);}

现在,当我尝试上传内容时出现以下错误:CORS 策略无法获取.所以我将这部分更改为以下内容并添加了 mode 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)])})

这奏效了.第二次尝试上传导致以下错误的文件:它说:语法错误:输入意外结束

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

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

第三次尝试上传文件,实际使用以下控制台结果:

ƒ json() { [本机代码] }

但谷歌驱动器中没有上传文件.我在某处遗漏了一些东西.也许我们应该创建一个文件夹并将文件放在那里.

哦,还有另一个信息:当我在谷歌应用程序 sript 中运行 doPost 函数时,它说:

TypeError:无法读取未定义的属性postData"(第 13 行)

EDIT2 -----------------------------------------

我添加了 https://drive.google.com/uc?export=download&id=###fileId### 到您的代码,一切正常.文件正在上传.

假设我们上传文件 test.mp3,我们称之为 testdata.这是我们收到的:

<代码>{文件名":测试数据",fileId":###some id##",fileUrl":https://drive.google.com/uc?export=download&id=###fileId###"}

现在,当我打开文件 url 时,浏览器会下载文件,但它的名称是:testdata,而不是 testdata.mp3.缺少文件类型结尾.

第二个任务:如果你点击链接,我想在浏览器中打开文件,当它的 mp3 文件例如我希望你可以在 webview 中播放声音,就像这里:https://musicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Descalo.mp3

希望你能指导我!

解决方案

我相信你的目标如下.

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

用法:

请执行以下流程.

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

Web Apps 的示例脚本是 Google Apps 脚本.所以请创建一个 Google Apps Script 项目.

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

2.准备脚本.

请将以下脚本(Google Apps 脚本)复制并粘贴到脚本编辑器中.此脚本适用于 Web 应用程序.

服务器端:Google Apps 脚本

请设置您要放置文件的文件夹 ID.

function doPost(e) {const folderId = "root";//或用于放置文件而不是root"的文件夹 ID,如果需要的话.const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);const 文件 = DriveApp.getFolderById(folderId).createFile(blob);const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};返回 ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);}

3.部署网络应用.

  1. 在脚本编辑器中,通过发布"打开一个对话框->部署为 Web 应用程序".
  2. 选择我"作为执行应用程序:".
    • 由此,脚本以所有者身份运行.
  3. 谁有权访问应用程序:"选择任何人,甚至匿名".
  4. 点击部署"按钮作为新的项目版本".
  5. 自动打开需要授权"对话框.

    1. 点击查看权限".
    2. 选择自己的帐户.
    3. 点击高级"在此应用未经验证".
    4. 点击转到###项目名称###(不安全)"
    5. 点击允许"按钮.

  6. 点击确定".
  7. 复制 Web 应用程序的 URL.这就像 https://script.google.com/macros/s/###/exec.
    • 当您修改 Google Apps 脚本时,请重新部署为新版本.这样,修改后的脚本就会反映到 Web Apps 中.请注意这一点.

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

客户端:HTML &Javascript

请将您的 Web 应用程序的 URL 设置为以下脚本.

<输入名称=文件"id="上传文件"类型=文件"><输入名称=文件名"id=文件名"类型=文本"><输入id=提交";类型=提交"></表单><脚本>const form = document.getElementById('form');form.addEventListener('提交', e => {e.preventDefault();const file = form.file.files[0];const fr = new FileReader();fr.readAsArrayBuffer(文件);fr.onload = f =>{const url = "https://script.google.com/macros/s/###/exec";//<--- 请设置 Web 应用程序的 URL.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))//<--- 您可以在此处检索返回值..catch(err => console.log(err));}});

结果:

运行上述脚本时,返回以下值.从中,您可以检索文件的 URL.

<代码>{文件名":### 输入的文件名###",fileId":###",fileUrl":https://drive.google.com/file/d/###/view?usp=drivesdk"}

注意:

参考:

so basically the task is quite simple, but I didn't find any workable solution for my problem. I have a huge upload script on my website (at the moment localhost), but lets reduce all the complexity to the only neccessary.

So I just want to upload a single file to Google Drive with Google App Script and receive the URL of it to save it in a var, to work with that information on a later point in my function.

Now the problem is I already have the form on my website, I dont want the form inside script.google.com as extra html, I want to transfer my user input to Google App Script, then upload it to google drive and return the url back to my website where I can save it into a var.

My problem now is, I cant put all the stuff together.

This is the form on my website (simplified):

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

So how can I upload my informations inside google drive and get back a result? How can I push the data in Google App Script without using iFrame or anything else?

THANK YOU!

**** Working example if html is in scripts.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();
  }
  
}

html in apps.googlescript

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

As reccomended Im going to describe the process here.

So we are on the website: www.example.com , there is a form with text input field and file field. Lets say we put in an image and call it example. Now if we press submit, I want to upload the image to google drive without any oAuth (Thats why we need to use google app script here) and name it to what we typed in the textfield. When the upload is done, I want the url of the image of google drive to be returned back to the website, so the form can continue working with the information. I want to save the returned url in a var then, to later on save it in a database. Thats why I need the result back to my website.

So scheme looks like the following:

Enter informations to form on website -> Redirected to google app script: take informations of website form field and upload file to google drive and name it like text input entry -> taking url of google drive as final result -> redirecting final url result back to website -> saving url result in var and continuing doing stuff from function on website -> at the end saving the informations from var to a database -> finish

------------------------------------------------ EDIT: ------------------

Thanks to @Tanaike Im a lot closer to the goal of my challenge here, so in order to see where I got stuck, I'm replicating my issue now:

I took the form with the script from your example:

<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.addEventListener('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>

and for google 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);
}

Now when i tried to upload something I had following error: CORS Policy not able to fetch. So I changed this part to the following and added mode 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)])})

This worked. Second try uploading the file caused in the following error: it says: syntax error: unexpected end of input

So I changed this line and removed the brackets from res.json

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

third try to upload the file actually worked with the following console result:

ƒ json() { [native code] }

But there is no file uploaded in google drive. Im missing something somewhere. Maybe we should create a folder and place the files in there.

Oh and another information: when i run doPost function in google app sript it says:

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

EDIT2 -----------------------------------------

I added https://drive.google.com/uc?export=download&id=###fileId### to your code and everything works fine. The file is getting uploaded.

Lets say we upload the file test.mp3 and we call it testdata. This is what we recieve:

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

Now when I open the file url, the browser downloads file but its called: testdata, not testdata.mp3. The filetyp ending is missing.

Second task: If you click the link, I want to open the file in browser, when its mp3 file for example i want that you can play the sound in webview, like it is here: https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Creative_Commons/Dead_Combo/CC_Affiliates_Mixtape_1/Dead_Combo_-_01_-_Povo_Que_Cas_Descalo.mp3

I hope you can guide me!

解决方案

I believe your goal as follows.

In this case, I think that your goal can be achieved using the Web Apps created by Google Apps Script.

Usage:

Please do the following flow.

1. Create new project of Google Apps Script.

Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.

If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.

2. Prepare script.

Please copy and paste the following script (Google Apps Script) to the script editor. This script is for the Web Apps.

Server side: Google Apps Script

Please set the folder ID that you want to put the file.

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. Deploy Web Apps.

  1. On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
  2. Select "Me" for "Execute the app as:".
    • By this, the script is run as the owner.
  3. Select "Anyone, even anonymous" for "Who has access to the app:".
  4. Click "Deploy" button as new "Project version".
  5. Automatically open a dialog box of "Authorization required".

    1. Click "Review Permissions".
    2. Select own account.
    3. Click "Advanced" at "This app isn't verified".
    4. Click "Go to ### project name ###(unsafe)"
    5. Click "Allow" button.

  6. Click "OK".
  7. Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
    • When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.

4. Upload a file from client side to server side.

Client side: HTML & Javascript

Please set the URL of your Web Apps to the following script.

<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.addEventListener('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>

Result:

When above script is run, the following value is returned. From this, you can retrieve the URL of the file.

{
  "filename": "### inputted filename ###",
  "fileId": "###",
  "fileUrl": "https://drive.google.com/file/d/###/view?usp=drivesdk"
}

Note:

References:

这篇关于使用 Google Apps 脚本将文件上传到我的谷歌驱动器(GOOGLE 中没有表格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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