Created
October 19, 2024 08:58
-
-
Save djalexkidd/c29f83b6dda38d1a8bbd94a4f2d1dcd4 to your computer and use it in GitHub Desktop.
Download and unzip file in GDScript (Godot Engine 4.3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Control | |
@onready var req := $HTTPRequest | |
# This function unzips the downloaded file | |
static func unzip(path_to_zip: String) -> void: | |
var zr : ZIPReader = ZIPReader.new() | |
if zr.open(path_to_zip) == OK: | |
for filepath in zr.get_files(): | |
var zip_directory : String = path_to_zip.get_base_dir() | |
var trimmed_path : String = "user://downloads" | |
var da : DirAccess = DirAccess.open(zip_directory) | |
# Create the base directory for the unzipped content | |
da.make_dir(trimmed_path) | |
# Make sure we are working within the newly created directory | |
da = DirAccess.open(trimmed_path) | |
# Create subdirectories recursively based on the filepath | |
da.make_dir_recursive(filepath.get_base_dir()) | |
print("Extracting: " + trimmed_path + "/" + filepath) | |
# Open the file for writing in the correct subdirectory | |
var fa : FileAccess = FileAccess.open("%s/%s" % [trimmed_path, filepath], FileAccess.WRITE) | |
if fa != null: | |
fa.store_buffer(zr.read_file(filepath)) | |
fa.close() | |
zr.close() | |
else: | |
print("Failed to open ZIP archive.") | |
# This function downloads a file from URL | |
# You need to connect a button node pressed() | |
func _on_button_pressed() -> void: | |
req.download_file = "user://test_archive.zip" | |
req.request("https://example.com/test_archive.zip") | |
# This function calls unzip() when the download has completed | |
# You need to connect a HTTPRequest node request_completed() | |
func _on_http_request_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void: | |
unzip("user://test_archive.zip") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment