Here, I will explain how to upload and display images without saving them in a folder in ASP.NET using C# and VB.NET. By using binary reader property in ASP.NET, we can upload and display images.
To upload and display images in ASP.NET without saving in folder, we need to create a new website in Visual Studio. Open aspx page and write the following code,
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>ASP.Net Upload and Preview Image without saving in C#, VB.Nettitle>
- <style type="text/css">
- #imgDetail
- {
- width: 30%;
- height: 30%;
- }
-
-
- <style>
- <head>
- <body>
- <form id="form1" runat="server">
- <div style=" width:50%">
- <asp:FileUpload ID="upload1" runat="server" />
- <asp:Button ID="btnPreview" runat="server" Text="Upload & Preview" onclick="btnPreview_Click" />
- <hr />
- <asp:Image ID="imgDetail" Visible="false" runat="server" />
- <div>
- </form>
- </body>
</head>
</style>
- </html>
After adding code in aspx page now open the code behind file and add the following namespaces.
C# Code
- using System;
- using System.IO;
After completion of adding namespaces you need to write the code as shown below,
- protected void btnPreview_Click(object sender, EventArgs e)
- {
- Stream strm = upload1.PostedFile.InputStream;
- BinaryReader reader = new BinaryReader(strm);
- Byte[] bytes = reader.ReadBytes(Convert.ToInt32(strm.Length));
- imgDetail.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
- imgDetail.Visible = true;
- }
VB.NET Code
- Imports System.IO
- Partial Class VBCode
- Inherits System.Web.UI.Page
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
- End Sub
- Protected Sub btnPreview_Click(ByVal sender As Object, ByVal e As EventArgs)
- Dim strm As Stream = upload1.PostedFile.InputStream
- Dim reader As New BinaryReader(strm)
- Dim bytes As [Byte]() = reader.ReadBytes(Convert.ToInt32(strm.Length))
- imgDetail.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length)
- imgDetail.Visible = True
- End Sub
- End Class
For Code Demo,