Convert image into binary format after uploading

21 Dec 20221 minute to read

By default, the file upload control saves the uploaded image files in physical directories. Also, you can convert the images into binary format at server-side before saving the uploaded images.
To retrieve binary format of image files, convert the posted file’s input stream into binary reader and read as bytes using ReadBytes method.

Refer to the below server-side code snippet

[[AcceptVerbs("Post")]
public IActionResult Save(IList<IFormFile> UploadFiles)
{
    IFormFile uploadedImage = UploadFiles.FirstOrDefault();
    if (uploadedImage.ContentType.ToLower().StartsWith("image/"))
    // Check whether the selected file is image
    {
        byte[] b;
        using (BinaryReader br = new BinaryReader(uploadedImage.OpenReadStream()))
        {
            b = br.ReadBytes((int)uploadedImage.OpenReadStream().Length);
            // Convert the image in to bytes
        }
        Response.StatusCode = 200;
    }
    return Content("");
}

NOTE

You can also explore ASP.NET MVC File Upload feature tour page for its groundbreaking features. You can also explore our ASP.NET MVC File Upload example to understand how to browse the files which you want to upload to the server.