title: Base64 String HTTP Post
body: <p>This is my last two questions essentially merged into one. <br />
  I'm building an app in Xamarin Studio for iOS using MonoTouch (C#) with a PHP HTTP Post backend.<br />
  <br />
  On adding the feature to allow users to upload their own images I have the convert the image object to a Base64 string to save in PHP.<br />
  <br />
  The process:<br />
  UIImage -> NSData -> byte[] -> Base64 String -> HTTP Post -> Decode Base64 string -> imagecreatefromstring -> imagejpeg to save in PHP
  <br/>
  <br />
  Here is the source I use in C# </p>
  
  <pre><code>public async void Post (string UID, string imageBase = null)
      {
          string data = "";
          if (imageBase != null) {
              data = string.Format ("METHOD=post&amp;UID={0}&amp;Image={1}", UID, imageBase);
          }
  
          HttpWebRequest r = await Info.createRequest (data);
          using (var resp = await Task.Factory.FromAsync&lt;WebResponse&gt; (r.BeginGetResponse, r.EndGetResponse, null)) {
              return;
          }
      }
  
  public static async Task&lt;HttpWebRequest&gt; createRequest (string json)
      {
          (new CancellationTokenSource ()).Dispose ();
          var request = WebRequest.Create (BaseUrl) as HttpWebRequest; 
          request.Method = "POST";    
          request.ContentType = "application/x-www-form-urlencoded";
  
          byte[] postData = Encoding.UTF8.GetBytes (json);
          using (var stream = await Task.Factory.FromAsync&lt;Stream&gt; (request.BeginGetRequestStream, request.EndGetRequestStream, request)) {
              await stream.WriteAsync (postData, 0, postData.Length);
          }
  
          return request;
      }
  </code></pre>
  
  <p>Here is the source I use in PHP</p>
  
  <pre><code>imagejpeg(imagecreatefromstring(base64_decode($_POST["Image"], TRUE)), "Users/Images/".$_POST["UID"]."/".md5(uniqid()).".png");
  </code></pre>
  
  <p>When I take the imageBase string from the C# code and manually paste it into the PHP code to replace $_POST["Image"], everything works fine. But it currently sends over a corrupted image stream, which I can only imagine is because the postData is encoded using UTF8, and when it's decoded on the server side, that I currently do not handle, it isn't decoded correctly. <br />
  <br />
  I was going to try to use a plain/text HTTP Post but that didn't seem to help, out of anything it mad it worse. </p>