Upload Binary data as HTTP POST

Below is the ASP.NET C# implementation of Uploading binary data like images as POST request to target URL:

private bool UploadFile(string PostURL)
{
    try
    {
        int contentLength = fileUpload.PostedFile.ContentLength;
        byte[] data = new byte[contentLength];
        fileUpload.PostedFile.InputStream.Read(data, 0, contentLength);

        // Prepare web request...
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(PostURL);
        webRequest.Method = "POST";
        webRequest.ContentType = "multipart/form-data";
        webRequest.ContentLength = data.Length;
        using (Stream postStream = webRequest.GetRequestStream())
        {
            // Send the data.
            postStream.Write(data, 0, data.Length);
            postStream.Close();
         }
         return true;
    }
    catch (Exception ex)
    {
         //Log exception here...
         return false;
     }
}

The binary data so posted can be retrieved on target post URL using below code:

byte[] Image = ReadFully(Request.InputStream);

.................

public static byte[] ReadFully(Stream input)
{
     byte[] buffer = new byte[16 * 1024];
     using (MemoryStream ms = new MemoryStream())
     {
         int read;
         while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
         {
             ms.Write(buffer, 0, read);
         }
         return ms.ToArray();
     }
}

This scenario is very handy specifically in establishing communication between two different web technologies. For example: You can POST image from flash to an ASP.NET web application where you can actually storing this image file.

(Visited 16,439 times, 1 visits today)