I have a console application that encodes an image as base64String and then sends it to a server as part of an http POST request.
Problem is, when I open it up to examine it server side, the data is no longer there.
Here is the code I’m using to send the string-
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(ip);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
string formPostString = "image=" + HttpUtility.UrlEncode(imageBase64String);
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(formPostString);
webRequest.ContentLength = buffer.Length;
using (Stream webStream = webRequest.GetRequestStream())
{
webStream.Write(buffer, 0, buffer.Length);
}
And the code I have handling it serverside-
private void OnRequest(object source, RequestEventArgs args)
{
IHttpClientContext context = (IHttpClientContext)source;
IHttpRequest request = args.Request;
ImageConverter imgConvert = new ImageConverter();
string imageBase64String = request.Form["image"].Value;
Image newImg = imgConvert.Base64StringToImage(imageBase64String);
newImg.Save(@"..\Images\test.png", System.Drawing.Imaging.ImageFormat.Png);
}
When it reaches the point of making the new Image object, the imageBase64String is null. I can’t seem to identify why this is happening.
The client code you have shown never sends a request. You must call
webRequest.GetResponse()for the request to be sent. But I would simplify this client code suing a WebClient:As far as your server side code is concerned you seem to be using some third party framework which you haven’t mentioned in your question. For example the following ASP.NET handler works perfectly fine (
~/UploadImage.ashx) with the client shown previously:But if we are going to upload files to a server, why reinventing wheels? Why using base64 when there’s
application/x-www-form-urlencodedwith a wheel reinvented Base64 encoding which hugely increases the request size when there’smultipart/form-data?So let’s improve our client to take advantage of this specifically designed for the purpose encoding. Let’s start by writing an extension method for the WebClient which will allow us to directly upload one or more files:
and then the client will look like this:
and the server we handler we have seen earlier:
Guess, what the next step in improvement of this code is? Answer: an asynchronous client request of course that will take advantage of I/O Completion Ports instead of blocking the calling thread while waiting for the file to be uploaded to the server.