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()'.
Updated: March 19, 2020
When V8 is enabled, it seems that this.parentNode
cannot be sent to Google Apps Script side. I'm not sure whether this is a bug or the specification. I think that this might be resolved in the future update. But as the current workaround, I would like to add one more sample script for uploading the file using Web Apps, dialog and sidebar.
In this case, the file is sent to Google Apps Script side as the byte array. And the file is created from the byte array at Google Apps Script side.
HTML & Javascript: index.html
<input id="file" type="file" onchange="saveFile(this)" />
<script>
function saveFile(f) {
const file = f.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
filename: file.name,
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler(e => console.log(e)).saveFile(obj);
};
fr.readAsArrayBuffer(file);
}
</script>
Google Apps Script: Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index.html');
}
function saveFile(e) {
var blob = Utilities.newBlob(e.bytes, e.mimeType, e.filename);
DriveApp.createFile(blob);
return "Done.";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…