Search Unity

Uploading image confusion

Discussion in 'Scripting' started by eco_bach, Jun 1, 2020.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Hi Some confusion over what steps are necessary to upload binary data(image) and then handle a JSON response.

    My understanding is that the uploading (and serialization) can be handled by the WWW class. ie the following in a coroutine

    Code (CSharp):
    1. int width = Screen.width;
    2.         int height = Screen.height;
    3.         Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
    4.         tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
    5.         tex.Apply();
    6.         //This basically takes a screenshot
    7.  
    8.         byte[] bytes = tex.EncodeToPNG();
    9.         Destroy(tex);
    10.  
    11.         // Create a Web Form, this will be our POST data
    12.         var form = new WWWForm();
    13.         form.AddField("somefield", "somedata");
    14.         form.AddBinaryData("file", bytes, "screenshot.png", "image/png");
    15.  
    16. //POST the screenshot
    17.         WWW w = new WWW(uploadUrl, form);
    How then would I handle the JSON response?
    Any feedback appreciated!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,738
    There's three things here:

    1. getting the texture data (you're just making a blank Texture, I assume for testing purposes) ready to go and into an array of bytes

    2. encoding and sending binary data to your server, however the server accepts it

    3. parsing the server response, however the server sends it. You would need to know this data shape.

    If the server has a swagger page then you can do all kinds of easy testing to construct your sending code. If not I would recommend starting from some tutorials for uploading binary data, assuming you can find one that matches the type of server you have or are contemplating.