- Home /
How do I retrieve a binary file with UnityWebRequest?
I'm building a game for WebGL.
My main goal is to save and load data from a binary file from my StreamingAssets folder.
I've read the documentation that says that I need to use UnityWebRequest for that, but it really doesn't explains anything..
I mostly don't understand how do I de-serialize my binary file and then serialize it again and use a web request to save it back.
Can I access it from UnityWebRequest.downloadHandler?
Answer by rh_galaxy · Jan 16, 2021 at 11:59 PM
This is what I use to get level files stored as either binary or text. Then I do this to call the subroutine. But this is a windows project not a webgl one if that makes any difference. Also I don't know of the StreamingAssets folder, this works on an url.
StartCoroutine(GetLevelFile(szMapFile, true));
You will have to write something similar to upload the file. How to create your binary data you can look up elsewhere.
internal string szLevelTextData;
internal byte[] aLevelBinaryData;
public IEnumerator GetLevelFile(string i_szFilename, bool i_bBinary)
{
bIsDone = false;
string url = WEB_HOST + "/user_levels/" + i_szFilename;
www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
if (!i_bBinary) szLevelTextData = www.downloadHandler.text;
else aLevelBinaryData = www.downloadHandler.data;
}
bIsDone = true;
}
Ok, so if I understand correctly, downloadHandler.data is the actual file represented as bytes[]?
If so, can I simply convert the bytes[] into my PlayerData type?
Or can I simply use de-serialization on the bytes[]?
Also, I already have a binary serialize and de-serialize script.
Yes, I think so. What makes me unsure if SendWebRequest is even the right way of accessing the data is that that you say you want to work in the Strea$$anonymous$$gAssets folder...
Would this work instead?
File.ReadAllBytes()
I didn't have to try that because your initial comment worked.
I now face another problem which is making a Put request to upload a new file.
I made a similar function to convert a PlayerData[] object to byte[]. But then when I send it through:
UnityWebRequest.Put(putURL,bytesData),
I print the error if there is and it prints:
HTTP/1.1 405 $$anonymous$$ethod Not Allowed.
I am hosting my site on HostGator, and after having a chat with tech support, they say they can't do anything about it..
Any idea how can I solve it?