+1 vote

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.

Godot version 3.4
in Engine by (172 points)

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.

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:
enter image description here
Result file (is longer than the picture):
enter image description here
(Both files are in the example project)

1 Answer

+1 vote
Best answer

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.

by (1,314 points)
selected by

Thank you very much!
Now everything is working.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.