Upload Binary Data using HTTP POST is a practical and efficient method for transferring files between client and server applications. In this blog, you’ll learn how to upload binary data from a web client to a server endpoint using C# and ASP.NET. This approach is particularly valuable when enabling communication between different technologies—such as posting an image from a Flash application to an ASP.NET backend—making cross-platform file transfers smooth and reliable.
Upload Binary Data using HTTP POST in C#
Here’s how you can read a binary file from a file upload control and post it to a target URL using the HttpWebRequest
class:
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 = "application/octet-stream"; //Update MIME type 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; } }
Tip: Always validate and sanitize uploaded data before processing it on the server.
Handling Binary Data on the Receiving Server
On the receiving side (target URL), you can read the raw binary stream from the HTTP request like this:
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(); } }
Once retrieved, you can process or store the file as needed (e.g., saving the image to disk or a database).
Use Cases & Scenarios
Cross-platform communication (e.g., Flash or JavaScript sending files to a .NET backend)
Mobile or desktop clients posting captured media files to a web API
Internal services exchanging binary content without complex form-data encoding
Best Practices
Use HTTPS to encrypt data in transit
Validate MIME types and file extensions
Limit file sizes to prevent abuse
Avoid
multipart/form-data
unless you’re sending additional fields;application/octet-stream
is simpler and cleaner for raw binary uploads