Surendra Sharma

Surendra Sharma

Search This Blog

Friday, June 19, 2015

1 line of code to preview image without uploading to server in ASP.NET

You say, you don’t want to upload image to server in ASP.NET website but still want to see the preview of image.

Here is a trick.

Create aspx page with below controls.

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Preview" OnClick="Button1_Click" /><br />
<img id="imgAny" runat="server" border="0" />

Write below C# code in button event.

protected void Button1_Click(object sender, EventArgs e)
    if (FileUpload1 != null && FileUpload1.HasFile)
        imgAny.Src = @"data:image/*;base64," + Convert.ToBase64String(FileUpload1.FileBytes);

Just fucking 1 line of code ;)

How it work?

Get the bytes of your image and convert into base 64. 
Set image mime type to image with base 64 and append the image string. 
That's it!!!

Please leave your comments or share this code if it’s useful for you.

1 comment:

  1. The title is misleading, because file is still uploaded to the server. You just don't save it, instead you convert it to base64 string.