0

I am trying to send an image over to the server via Unity. I am able to achieve sending image via command prompt with the below code:

curl -H "Authorization: Token 555myToken555" -F "id=Image01" -F "image=@/home/example.png" https://mywebsite.com

But the same way I cannot achieve using Unity's Web Request. Where do I provide the "id=Image01" and http link? Also is Put() better in performance than Post()?

public Texture2D tex;

UnityWebRequest unityWebRequest= UnityWebRequest.Put( tex,  texture.EncodeToPNG());

unityWebRequest.SetRequestHeader("Authorization", "Token 555myToken555");

unityWebRequest.SendWebRequest();
Hamdi
  • 187
  • 1
  • 2
  • 11

1 Answers1

1

First of all the first parameter of UnityWebRequest.Put is not your tex where the ToString implicitly returns tex.name but rather the URI!

And then note that curl -F

(HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC2388. This enables uploading of binary files etc

This anyway uses POST, not PUT.

And in a UnityWebRequest.Post you can easily add form parts using e.g. a WWWForm and AddField and AddBinaryData like e.g.

public void UploadTexture(Texture2D tex)
{
    StartCoroutine(UploadTextureRoutine(tex));
}

private IEnumerator UploadTextureRoutine(Texture2D tex)
{
    var bytes = tex.EncodeToPNG();
    var form = new WWWForm();
    form.AddField("id", "Image01");
    form.AddBinaryData("image", bytes, $"{tex.name}.png", "image/png");
    
    using(var unityWebRequest = UnityWebRequest.Post("https://mywebsite.com", form))
    {
        unityWebRequest.SetRequestHeader("Authorization", "Token 555myToken555");
    
        yield return unityWebRequest.SendWebRequest();
    
        if (unityWebRequest.result != UnityWebRequest.Result.Success) 
        {
            print($"Failed to upload {tex.name}: {unityWebRequest.result} - {unityWebRequest.error}");
        }
        else 
        {
            print($"Finished Uploading {tex.name}");
        }
    }
}

Also is Put() better in performance than Post()

They are Completely different Protocols.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Hey thanks alot for the detailed explanation :) I have used your code but I am getting few errors. I am assigning the texture png in the inspector and this texture is Read/Write enabled. But still I get the following erros: ```Unsupported texture format - Texture2D::EncodeTo functions do not support compressed texture formats.``` and ```UnassignedReferenceException: The variable tex of MyScript has not been assigned.``` – Hamdi Apr 13 '21 at 10:03
  • I anyway wanted to send a screenshot of the screen so I made a workaround for that with your code.:) – Hamdi Apr 13 '21 at 10:26