google-apps-script - 如何在 Google 脚本中上传文件到驱动器
问题描述
我有一个脚本,可让您从驱动器中选择一个文件到我的应用程序中。我希望能够从计算机而不是驱动器中选择文件,这可能吗?也许某种 htmlservice 可以做到这一点,但我不知道如何从中获取 blob 进行上传。
编辑:
包括在评论中提出的内容。使用以下代码,我确实将文件上传到了想要的文件夹中,但即使它已经上传,它也会挂在“上传中。请稍候......”。
代码.gs
function showPicker() {
var html = HtmlService.createHtmlOutputFromFile('FileSelect.html')
.setWidth(600)
.setHeight(200)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'Select a file');
}
function uploadTheFile(theForm) {
Logger.log("TEST");
Logger.log(theForm);
var fileBlob=theForm.fileToLoad;
Logger.log(fileBlob);
var fldr = DriveApp.getFolderById('1dUfcChYwwSX3NLIEGg7g5MetpXfqu_pz');
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;
}
文件选择.html
<!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>
<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>
解决方案
为了使解决方案按预期工作,我建议您对提供的代码进行以下更改:
var fi=formatFileName(file);
从uploadTheFile()
函数中删除,因为该formatFileName()
方法不存在且不需要;更新
var fileInfo
到这个:
var fileInfo={'name':file.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName()};
因此,基本上,formatFileName()
您将直接使用file.getName()
来检索文件名,而不是使用 。
此外,这里有一些链接可能会对您有所帮助:
推荐阅读
- amazon-web-services - 如何只允许将文件从 S3 下载到 AWS Cognito 用户?
- python - Python加速函数来分配时间相关的元素
- css - 在 CSS 文件中访问 Laravel 的公共文件夹
- java - 在spring(boot)启动时扫描使用自定义@Annotation注释的任意目标(TYPE,METHOD,FIELD)
- javascript - Google Visualization API 在同一个 HTML 上加载 2 个脚本
- automation - 如何仅将 pdf 的特定页面内容复制到剪贴板?
- javascript - 文件(图像)不存储到本地存储
- javascript - 如何使用 javascript 或 jquery 等下载图像
- elasticsearch - 如何在elasticsearch脚本中将字段与_id进行比较?
- ruby-on-rails - 如果条件通过,则运行一个块