- Home /
Using UnityWebRequest POST to upload image files
Hello!
I'm trying to upload image files using the UnityWebRequest class.
My code looks like this:
//get image
var imageData = _sprite.texture.GetRawTextureData();
var data = new List<IMultipartFormSection> {
new MultipartFormDataSection("foo", "bar"),
new MultipartFormFileSection("myImage", imageData, "test.png", "image/png")
};
//init handshake
var handshake = UnityWebRequest.Post("http://mypage/uload.php", data);
var request = handshake.SendWebRequest();
//response
request.completed += (action) => {
if (!handshake.isHttpError && !handshake.isNetworkError) {
Debug.Log(handshake.downloadHandler.text);
}
};
The response looks like this:
Array (
[myImage] => Array
(
[name] => test.png
[type] =>
[tmp_name] =>
[error] => 3
[size] => 0
) )
Does anyone have an idea what i'm doing wrong?
Answer by eelcooe · Dec 06, 2017 at 10:02 PM
Ended up using the WWW class. Applied exactly the same logic and apparently this works just fine so I assume it's something to do with the UnityWebRequest class.
Answer by Bunny83 · Dec 06, 2017 at 05:50 PM
GetRawTextureData is not a PNG image. It returns the raw data as it is stored in the GPU memory. It's not a file format. You should use EncodeToPNG. I'm not sure if that's your only issue. However webservers might reject posted data which doesn't match the specified mime format.
Another problem could be that you do not wait for the upload to finish. Since you create the webrequest instance locally inside a method it might get garbage collected before the upload has finished. You should use a coroutine and wait for the upload to finish.
PHP error code 3 is "UPLOAD_ERR_PARTIAL" which actually tells you that the upload was interrupted /aborted.
Tried using coroutine, same result. The request is sent async so my initial event would work the same way anyway.
Used EncodeToPNG(), same result :/