Downloading Save Data from Web Build?

Godot Version

4.5.1-stable

Question

I am wanting users to be able to download and import their save data to their computers from the web build of the tool im creating. The file is in JSON format using this code to save:

func SaveDataJSON(data: Dictionary, fileName: String) -> void:
	var file := FileAccess.open(FILE_PATH + fileName + FILE_TYPE_JSON, FileAccess.WRITE)
	if file:
		file.store_string(JSON.stringify(data, "\t"))
		file.close()
	else:
		push_error("Failed to save")

I understand at the basic is should use JavaScriptBridge, and download buffer. The only information ive seen is showing how to convert images and strings to the buffer, so im unsure what to really do for json or dictionaries.

You should read the data back as a string and use JavascriptBridge.download_buffer() like:

extends Node


@onready var button: Button = $Button


func _ready() -> void:
	var data = {
		"hello": "world",
		"int": 10,
		"float": 562343.2384,
		"obj": {
			"f1": true,
			"f2": "potato"
		}
	}
	var f = FileAccess.open("user://save.json", FileAccess.WRITE)
	f.store_string(JSON.stringify(data))
	f.close()
	button.pressed.connect(_download)



func _download() -> void:
	var json = FileAccess.get_file_as_string("user://save.json")
	JavaScriptBridge.download_buffer(json.to_utf8_buffer(), "save.json")
2 Likes

this is it! or close enough, while going to do it as a string saw fileaccess has “get_file_as_bytes” which is already a packed byte array.

dont know why i didnt think to like in file access docks for an answer but it happens, Thank you for the help!