Saturday, July 10, 2021

ASP.Net:Convert HttpPostedFile to Base64 string using C# and VB.Net

ASP.Net:Convert HttpPostedFile to Base64 string using C# and VB.Net

In this article I will explain with an example, how to convert HttpPostedFile class object to Base64 string using C# and VB.Net.

The HttpPostedFile class object holds the File data for the ASP.Net FileUpload control.

In order to convert HttpPostedFile class object to Base64 string, first the HttpPostedFile class object is converted to Byte Array using the ReadBytes method of the BinaryReader class.

Then the Byte Array is converted to Base64 string using the ToBase64String method.

HTML Markup

<form id="form1" runat="server">

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Text="Upload"

    onclick="btnUpload_Click" />

<hr />

<asp:Image ID="Image1" Visible = "false" runat="server" Height = "100" Width = "100" />

</form>

Above you will see a FileUpload control to upload the Image File, a Button control to trigger the File upload process and an Image control to display the uploaded image file.

Convert HttpPostedFile to Base64 string using C# and VB.Net

Below is the code that is being executed when the Upload button is clicked.

C#

protected void btnUpload_Click(object sender, EventArgs e)

{

    System.IO.Stream fs = FileUpload1.PostedFile.InputStream;

    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

    Byte[] bytes = br.ReadBytes((Int32)fs.Length);

    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

    Image1.ImageUrl = "data:image/png;base64," + base64String;

    Image1.Visible = true;

}

VB.Net

Protected Sub btnUpload_Click(sender As Object, e As EventArgs)

    Dim fs As System.IO.Stream = FileUpload1.PostedFile.InputStream

    Dim br As New System.IO.BinaryReader(fs)

    Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Integer))

    Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)

    Image1.ImageUrl = "data:image/png;base64," & base64String

    Image1.Visible = True

End Sub

No comments:

Post a Comment

DotNet Latest Technologies

  I'm not sure exactly what you are looking for or how "recent" the technologies that you might wan to look into are, but I...