Skip to content

Instantly share code, notes, and snippets.

@nisovin
Last active May 30, 2022 14:02
Show Gist options
  • Save nisovin/f230240003bbc404d203a88f78bd39a0 to your computer and use it in GitHub Desktop.
Save nisovin/f230240003bbc404d203a88f78bd39a0 to your computer and use it in GitHub Desktop.
Godot Web File Open/Save Dialogs
extends Control
func _ready():
WebFiles.connect("file_opened", self, "_on_file_opened")
func _on_Button_pressed():
WebFiles.open_file(".jpg,.jpeg")
func _on_file_opened(file, content):
$Label.text = file
var img = Image.new()
img.load_jpg_from_buffer(content)
var tex = ImageTexture.new()
tex.create_from_image(img)
$TextureRect.texture = tex
func _on_Button2_pressed():
WebFiles.save_file("filename.txt", "This is some content!", "text/plain")
<!-- this goes in the export window -->
<script>
window.GodotWebFiles = {
open_file_callback: null,
open_file: (accept, text, multiple) => {
if (window.GodotWebFiles.open_file_callback == null) return;
let input = document.createElement('input');
input.type = 'file';
if (accept != "") {
input.setAttribute("accept", accept);
}
if (multiple) {
input.setAttribute("multiple", "multiple");
}
input.onchange = e => {
for (let i = 0; i < e.target.files.length; i++) {
let file = e.target.files[i];
let reader = new FileReader();
if (text) {
reader.readAsText(file, 'UTF-8');
} else {
reader.readAsArrayBuffer(file);
}
reader.onload = readerEvent => {
let result = readerEvent.target.result;
if (!text) {
result = new Uint8Array(result);
}
window.GodotWebFiles.open_file_callback(file.name, text, result);
}
}
}
input.click();
}
}
</script>
# Add this file as a singleton
extends Node
signal file_opened
var godot_web_files_obj
var open_file_callback
func _ready():
if OS.has_feature("HTML5"):
godot_web_files_obj = JavaScript.get_interface("GodotWebFiles")
open_file_callback = JavaScript.create_callback(self, "_on_file_opened")
godot_web_files_obj.open_file_callback = open_file_callback
func open_file(accept = "", text = false, multiple = false):
if godot_web_files_obj != null:
godot_web_files_obj.open_file(accept, text, multiple)
func save_file(file, content, mime = "application/octet-stream"):
if content is String:
content = content.to_utf8()
if not content is PoolByteArray:
assert(false)
JavaScript.download_buffer(content, file, mime)
func _on_file_opened(data):
var file = data[0]
var text = data[1]
var content = data[2]
if !text:
content = _convert_obj_to_byte_array(content)
emit_signal("file_opened", file, content)
func _convert_obj_to_byte_array(obj):
var bytes = PoolByteArray()
bytes.resize(obj.length)
for i in obj.length:
bytes[i] = obj[i]
return bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment