所以基本上任务很简单,但我没有找到任何可行的解决方案来解决我的问题。我的网站上有一个巨大的上传脚本(目前是本地主机),但让我们将所有复杂性降低到唯一必要的程度。
因此,我只想使用 Google App Script 将单个文件上传到 Google 云端硬盘,并接收它的 URL 以将其保存在 var 中,以便在我的函数中稍后使用该信息。
现在的问题是我的网站上已经有了表格,我不想将 script.google.com 中的表格作为额外的 html,我想将我的用户输入传输到 Google App Script,然后将其上传到 google drive 并返回 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>
那么我怎样才能在谷歌驱动器中上传我的信息并取回结果呢?如何在不使用 iFrame 或其他任何东西的情况下将数据推送到 Google App Script 中?
谢谢你!
\*\*\*\* 如果 html 在 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();
}
}
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 中,稍后再将其保存在数据库中。这就是为什么我需要将结果返回到我的网站。
所以方案如下所示:
输入信息以在网站上形成 -> 重定向到谷歌应用程序脚本:获取网站表单字段的信息并将文件上传到谷歌驱动器并像文本输入条目一样命名 -> 将谷歌驱动器的 url 作为最终结果 -> 将最终 url 结果重定向回来到网站 -> 将 url 结果保存在 var 中并继续从网站上的功能中执行操作 -> 最后将信息从 var 保存到数据库中 -> 完成
- - - - - - - - - - - - - - - - - - - - - - - - 编辑: ——————
感谢@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.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>
和谷歌脚本:
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 error: unexpected end of input
所以我更改了这一行并从 res.json 中删除了括号
JSON.stringify([...new Int8Array(f.target.result)])})
.then(res => res.json)
第三次尝试上传文件实际使用以下控制台结果:
ƒ json() { [native code] }
但是谷歌驱动器中没有上传文件。我在某处遗漏了一些东西。也许我们应该创建一个文件夹并将文件放在那里。
哦,还有另一个信息:当我在 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_Descalo.mp3
我希望你能指导我!
原文由 Marcel Dz 发布,翻译遵循 CC BY-SA 4.0 许可协议
我相信你的目标如下。
在这种情况下,我认为您的目标可以使用由 Google Apps 脚本创建的 Web 应用程序来实现。
用法:
请执行以下流程。
1.新建Google Apps Script项目。
Web Apps 的示例脚本是 Google Apps 脚本。所以请创建一个 Google Apps Script 项目。
如果想直接创建,请访问 https://script.new/ 。在这种情况下,如果您未登录 Google,则会打开登录屏幕。所以请登录谷歌。这样,Google Apps Script 的脚本编辑器就打开了。
2.准备脚本。
请将以下脚本(Google Apps 脚本)复制并粘贴到脚本编辑器中。此脚本用于 Web 应用程序。
服务器端:Google Apps 脚本
请设置您要放置文件的文件夹ID。
3. 部署网络应用程序。
https://script.google.com/macros/s/###/exec
。4. 从客户端上传文件到服务器端。
客户端:HTML 和 Javascript
请将您的 Web 应用程序的 URL 设置为以下脚本。
结果:
运行上述脚本时,将返回以下值。从这里,您可以检索文件的 URL。
笔记:
参考: