How to convert image to binary in React File Upload
By default, the React File Upload component saves uploaded image files to physical directories on the server. For advanced scenarios requiring binary data manipulation, convert images to binary format server-side before storage. This approach enables scenarios such as database storage, image processing, or custom validation.
To retrieve the binary format of uploaded image files, convert the posted file’s input stream into a binary reader and read the data as bytes using the ReadBytes method. The following code snippet demonstrates this server-side implementation:
using System;
using System.IO;
using System.Linq;
using System.Web;
[AcceptVerbs("Post")]
public void Save()
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Length > 0)
{
var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadFiles"];
if (httpPostedFile != null)
{
byte[] fileBytes;
using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream))
{
fileBytes = br.ReadBytes((int)httpPostedFile.InputStream.Length);
// bytes will be stored in variable fileBytes
}
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusCode = 200;
Response.Status = "200 Success";
Response.End();
}
}
}
catch (Exception e)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusCode = 204;
Response.Status = "204 No Content";
Response.StatusDescription = e.Message;
Response.End();
}
}See Also
You can also explore React File Upload feature tour page for its groundbreaking features. You can also explore our React File Upload example to understand how to browse the files which you want to upload to the server.