2017-02-02 31 views
1

我想要http将图像从html表单发布到谷歌应用程序脚本web应用程序,然后将该图像添加到谷歌驱动器。如何将jpg或png转换为Google应用程序脚本上的blob?

我的应用程序脚本如下。

function doPost(e){ 
    var date = new Date(); 
    var timestamp = date.toString() 
    var adress = e.parameter.adress; 
    var cost = e.parameter.cost; 
    var item = e.parameter.item; 
    var check = e.parameter.image; 

    //add file to drive 
    var destination_id = "some ID" 
    var destination = DriveApp.getFolderById(destination_id); 
    destination.createFile(check); 
}; 

当我执行时,它返回一个错误; cannot find method: createFile(String)

我认为这是因为“check”是一个字符串,我想将提交的图像转换为Blob。 我该怎么做?

+0

本文介绍如何上传图像到GAS:[GAS-upload-image](http://stackoverflow.com/questions/21593249/uploading-images-to-a-google-spreadsheet-using-apps-脚本) –

回答

2

下面的样本如何?添加“getAs()”。 https://developers.google.com/apps-script/reference/drive/file#getAs(String)

这些都是非常简单的html和gas脚本,我用于这个测试。

HTML:此文件名是“form.html”。

<form> 
    <input type="file" name="imageFile"> 
    <input type="button" value="ok" onclick="google.script.run.upload(this.parentNode)"> 
</form> 

GAS脚本:

function doGet() { 
    return HtmlService.createHtmlOutputFromFile('form.html'); 
} 

function upload(e) { 
    var destination_id = "some ID"; 
    var img = e.imageFile; 
    var contentType = "image/jpeg"; 
    var destination = DriveApp.getFolderById(destination_id); 
    var img = img.getAs(contentType); 
    destination.createFile(img); 
} 

对于此示例脚本,如果要保存为JPEG文件,请从 '图像/ PNG' 到 '图像/ JPEG' 改变 '的contentType'。当您上传contentType为'image/jpeg'的png文件时,png文件将由'getAs()'转换为jpeg文件。

+0

感谢您的帮助。但是,当我执行你的代码时,我得到一个错误:找不到函数getAs for Object submitted_image.png。当我看着“typeof check”时,它是“字符串”。我认为这是问题。 – Katshun0307

+0

您是否将其用作Google云端硬盘上的谷歌应用脚​​本?如果你这样做,我可以问你关于请求方法吗?你如何请求这个“doPost”?我认为通过请求方法得到的文件数据有错误的问题。因为当我使用“getAs()”测试发布请求时,它工作正常。 – Tanaike

+0

<脚本类型= “文本/ JavaScript的”> \t \t功能提交(){ \t \t \t的document.getElementById( “formId”)提交(); \t \t} \t \t <表格ID = “formId” 行动= “https://script.google.com/macros/s/hogehoge/exec” 方法= “POST” 目标= “fake_target”> \t //输入// \t – Katshun0307

相关问题