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
              => 0
        ) )

Does anyone have an idea what i’m doing wrong?

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.

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.