Search Unity

Question Sending image over UnityWebRequest

Discussion in 'Scripting' started by saifshk17, Apr 13, 2021.

  1. saifshk17

    saifshk17

    Joined:
    Dec 4, 2016
    Posts:
    488
    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:

    Code (CSharp):
    1. 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()?

    Code (CSharp):
    1. public Texture2D tex;
    2.  
    3. UnityWebRequest unityWebRequest= UnityWebRequest.Put( tex,  texture.EncodeToPNG());
    4.  
    5. unityWebRequest.SetRequestHeader("Authorization", "Token 555myToken555");
    6.  
    7. unityWebRequest.SendWebRequest();
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    You're sending the image bytes directly as the body of the request while curl creates a
    multipart/form-data
    body, encoding multiple fields.

    To do the same with UnityWebRequest, you need to use WWWForm to set both an id and image field (see the first example on that page that uploads an image and sets an additional form field).