Search Unity

Binary upload with headers

Discussion in 'Scripting' started by kujo, Oct 1, 2014.

  1. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Hi,

    I'm trying upload an image using the WWWForm class, but I also need to add a cookie to the header for my session authentication. For a normal POST request this works fine, but when I add binary data into it, it doesn't work.

    My code is as follows:

    Code (csharp):
    1.  
    2. private static WWW BuildRequest(string path, Dictionary<string, string> paramList = null, byte[] binaryData = null)
    3.     {
    4.         string url = string.Format("{0}{1}/?t={2}", apiUrl, path, Utils.UnixTimeStampUTC());
    5.         if (paramList != null && binaryData == null)
    6.         {
    7.             WWWForm postForm = new WWWForm();
    8.             foreach (var key in paramList.Keys)
    9.             {
    10.                 postForm.AddField(key, paramList[key]);
    11.             }
    12.  
    13.             var jar = SessionCookie();
    14.             var headers = postForm.headers;
    15.  
    16.             foreach (var i in jar.Keys)
    17.             {
    18.                 headers.Add(i, jar[i]);
    19.             }
    20.  
    21.             if(binaryData != null)
    22.                 postForm.AddBinaryData("image_data", binaryData, "screenshot.png", "image/png");
    23.  
    24.             return new WWW(url, postForm.data, headers);
    25.         }
    26.         else
    27.         {
    28.             return new WWW(url, null, SessionCookie());
    29.         }
    30.     }
    31.  
    The only way I can get it to work is to change this:

    Code (csharp):
    1.  
    2. return new WWW(url, postForm.data, headers);
    3.  
    to this:

    Code (csharp):
    1.  
    2. return new WWW(url, postForm);
    3.  
    But that doesn't allow me to pass my extra headers in then.

    I've used Charles to look at the differences and when I pass in my header, my content type is appliction/x-www-form-urlencoded, but when I don't pass any headers in, the content type is multipart/form-data;

    Am I doing some thing wrong here?