我准备了一个带有Upload表单的简单Google Apps脚本,可以让没有Google帐户的朋友上传一些文件(不同类型的图片,docx,png等;较小的文件-10MB以下)
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var mainFolder = "Tmp_Uploads";
var folder = DriveApp.getFoldersByName(mainFolder).next();
var file = folder.createFile(form.myFile);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
机制有效->上传文件后,显示在Google云端硬盘的“ Tmp_Uploads”文件夹中。 但是当我将其下载到PC时->文件已损坏。
我用.jpg,.png,.doc对其进行了测试,并且它们都坏了-无法打开它们(它们的尺寸也与原始尺寸不同)。
当我上传简单的.txt文件->时,效果很好。
疑问:
预先加油,谢谢!
答案 0 :(得分:0)
在调用google脚本uploadFiles()函数之前,请尝试在HTML中使用此Javascript函数。
<script>
function uploadFile(form) {
const file=form.File.files[0];
const fr=new FileReader();//all this FileReader code originally came from Tanaike
fr.onload=function(e) {
const obj={filename:file.name,mimeType:file.type,bytes:[...new Int8Array(e.target.result)]};
google.script.run.uploadFiles(obj);
}
fr.readAsArrayBuffer(file);
}
</script>
然后您的Google脚本功能如下:
function uploadFiles(form) {
var mainFolder = "Tmp_Uploads";
var folder = DriveApp.getFoldersByName(mainFolder).next();
var blob = Utilities.newBlob(form.bytes, form.mimeType, form.filename);
var file=folder.createFile(blob);
return "File uploaded successfully " + file.getUrl();
}
如果您的表单中有更多数据,而不仅仅是文件上传,那么请看一下此示例。
<script>
function uploadFile(form) {
console.log('form.elements.Destination.value= %s',form.elements.Destination.value);
console.log('format.elements.FileName.value= %s',form.elements.FileName.value);
$('#msg').css('display','block');
$('#msg').html('UpLoading...Please Wait');
const file=form.File.files[0];
const fr=new FileReader();//all this FileReader code originally came from Tanaike
fr.onload=function(e) {
const obj={FileName:form.elements.FileName.value,Destination:form.elements.Destination.value,mimeType:file.type,bytes:[...new Int8Array(e.target.result)]};//this allowed me to put the rest of the Form.elements back into the object before sending it to google scripts
google.script.run
.withSuccessHandler(function(msg){
$('#msg').css('display','block');
$('#msg').html(msg);//I returned a message after the download
})
.uploadFile(obj);
}
fr.readAsArrayBuffer(file);
}
</script>
<form>
<br /><select id="sel1" name="Destination"></select> Upload Destination
<br /><input type="text" name='FileName' /> File Name
<br /><input type="file" name='File'; />
<br /><input type="button" value="Upload" onClick="uploadFile(this.parentNode);" />
<br /><input type="button" value="Close" onclick="google.script.host.close();" />
<div id="msg"></div>
</form>