【发布时间】:2020-08-27 00:20:32
【问题描述】:
我有一个 Google Apps Script 网络应用程序,用于将表单响应保存在电子表格和 Google 驱动器中。
其中一个表单字段将文件保存在 Google 云端硬盘中,但它不起作用。
HTML 表单(由于表单大小,我已将其缩小)
<form id="miformulario" onsubmit="envio_formulario(this)">
<input type="text" id="padre" name="padre" maxlength=8 value="" required class="form-control"/>
<input type="email" id="mailp" name="mailp" value="" required class="form-control" />
<input type="file" name="documentacion" >
<button type="submit" class="btn btn-outline-secondary">Tramitar solicitud</button>
</form>
form.js
function envio_formulario(Objetoformulario)
{
var values = $('#miformulario').serializeArray();
var data = {};
$(values ).each(function(index, obj){
data[obj.name] = obj.value;
});
var invalid = Objetoformulario.querySelectorAll(':invalid');
if ( invalid.length == 0 ) // Si no hay errores grabamos los datos
{
const file = Objetoformulario.documentacion.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler(ficherocargado).cargarFichero(obj, data);
};
fr.readAsArrayBuffer(file);
}
}
代码.gs
function cargarFichero(file, form){
console.log(file.mimeType); //Output => audio/mpeg
console.log(typeof file.bytes); //Output => Object
console.log(file.bytes); //Output => [ 82, 73, 70, 70, -128.......]
var fichero = Utilities.newBlob(file.bytes, file.mimeType, "file");
console.log(fichero) // Output => undefined
if (fichero){
var documentosI = "xxxxxx";
var documentosII = cif + "_" + cliente;
var carpetaI, carpetasI = DriveApp.getFoldersByName(documentosI);
var carpetaII, carpetasII = DriveApp.getFoldersByName(documentosII);
if (carpetasI.hasNext()) {
carpetaI = carpetasI.next();
}
if (carpetasII.hasNext()) {
carpetaII = carpetasII.next();
}
else {
carpetaII = carpetaI.createFolder(documentosII);
}
var documentacion = carpetaII.createFile(fichero);
documentacion.setName(cif + " _ " + cliente + " _ ATEN");
var id_documento = documentacion.getId();
}
}
数据被正确发送到 code.gs,在服务器函数中我收到了 file.bytes 和 file.mimeType,但是当我尝试创建 newBlob 它没有创建任何东西时,返回为未定义。有什么想法吗?
【问题讨论】:
-
在
newBlob(data, contentType)方法中数据应该是一个字节数组。根据文档,newBlob(data, contentType, name)中的数据应该是字符串。我认为您正在使用字节大小。如果我错了,请原谅我。我不理解第一个文件中的纯 JavaScript。我说的只是第二个文件。 -
newBlob(...) 的第一个参数应该是 blob 的字符串,假定为 UTF-8。您的代码中的
file.bytes不是字符串。此外,cargafichero(...)参数也限制了数据类型。详情请见google.script.run manual。 -
@TylerRake 我的代码有错误。数据对象 (file.bytes) 是一个字节数组,输出 (300000) 是 file.bytes.length。对不起,我已经更新了问题,它仍然无法正常工作......
-
@АлександрЕрмолин 谢谢。我在代码解释中有一个错误,newBlob 输出的第一个参数实际上是字节大小(file.bytes.length)。我检查了 google.script.run 限制,但我认为我没有违反任何限制...
-
你能显示
file.type和file.bytes的输出吗?