How do I convert jpg or png to blob on google app script?

一世执手 提交于 2019-12-08 04:13:20

问题


I want to http post an image from html form to google apps script web app, and then add that image to google drive.

my apps script is below.

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);
};

when I execute, it returns a error ; cannot find method: createFile(String)

I think this is because "check" is a string, and I want to convert the submitted image to Blob. How can I do this?


回答1:


How about following sample? Added "getAs()". https://developers.google.com/apps-script/reference/drive/file#getAs(String)

These are very simple html and gas script I used for this test.

HTML: This file name is "form.html".

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

GAS script:

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);  
}

For this sample script, if you want to save as a jpeg file, please change 'contentType' from 'image/png' to 'image/jpeg'. When you upload png file for contentType of 'image/jpeg', the png file is converted to jpeg file by 'getAs()'.



来源:https://stackoverflow.com/questions/41994351/how-do-i-convert-jpg-or-png-to-blob-on-google-app-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!