How can I transfer a file from a Client to a Server?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gamemap

I want to transfer a file from a Godot client to a Godot server, but it doesn`t work.

I used the file.get_buffer() method in a loop, stored everything in a PoolByteArray and put it in a new file with file.store_buffer.

Here is a example project.

I hope someone can help me.

You could try encoding the binary data to Base64 and sending it as a string, but it will cause the binary data to grow by at least 33% over the wire. The Marshalls singleton offers methods to encode and decode Base64.

Calinou | 2021-11-21 14:31

Sorry, I expressed myself incorrectly.

When I load a file with file.get_buffer() and store it (in the same project) with file.store_buffer() the result is wrong. The server and the client are just the case where I want to use it.

Should I make a bug report? (Could you test it?)

File before sending:


Result file (is longer than the picture):

(Both files are in the example project)

Gamemap | 2021-11-21 17:44

:bust_in_silhouette: Reply From: AlexTheRegent

Your problem is that you misused for cycle. When you write for cycle as for index in 10 it will be executed 10 times. In your case, you have for bytes in file.get_len():. If your file has 1000 bytes, then it will be executed as for bytes in 1000, i.e. this for cycle will be executed 1000 times. And this is obviously not what you want. Instead of your cycle

for bytes in file.get_len():
	bytearray += file.get_buffer(bytes)

you just have to read file as

bytearray = file.get_buffer(file.get_len())

After this change, everything will work as expected.

Right now your code prints a lot of garbage because file.get_buffer attempts to read content that is outside of your file (if you file has 4 bytes, then at first cycle step you will read 1 byte (3 remain), at second step 2 bytes (1 byte remain), and at 3’rd step you will try to read 3 bytes, but only 1 byte remain, so you would grab 2 bytes of garbage. Last step will have 4 bytes of garbage, because you already outside of your file, experiencing undefined behavior.

Thank you very much!
Now everything is working.

Gamemap | 2021-11-22 15:43