How to upload a image in ASP.NET using VB.NET

In this article,I am going to show how we can upload a image in ASP.NET.
  • 12458

In this article,I am going to show how we can upload a image in ASP.NET. 

Fileuploading the files:

- Use FileName property to get the selected file name from client.
- To get path of a folder on server use Server.MapPath() method.
- Use SaveAs() method of fileupload controls to upload a file.
- To restrict the specific kind of file get extension of it using System.IO.Path.GetExtension()method.

Example:

Drag upload control, one Button and one image control on the form. form looks like this.

upload1.gif
 

Figure1.

Now click on the source of the above form and add the below code.
 

 

Getting reference of a control in a webpage:

 -Use document.getElementById()method

 

Code in C#:

 

<script type="text/javascript">

        function ShowImage()

        {

            var f=document.getElementById("FileUpload1");

            var img=document.getElementById("Image1");

            img.src=f.value;

        }

    </script>

 

Code in VB.NET:

 

<script type="text/javascript">

    Private Function ShowImage() As [function]

       Dim f = document.getElementById("FileUpload1")

       Dim img = document.getElementById("Image1")

       img.src = f.value

End Function

 

Using Client Side Events on Server Side Control

 

-Use Attributes collection of server side controls to add the client side event and Java Script functions to be executed on client side

 

Example:

 

Code in C#:

 

protected void Page_Load(object sender, EventArgs e)

        {

            FileUpload1.Attributes.Add("onFocus", "ShowImage()");

        }

 

Code in VB.NET:

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        FileUpload1.Attributes.Add("onFocus", "ShowImage()")

    End Sub

To get path of a folder on server use Server.MapPath() method.

Code in C#:

protected void Button1_Click(object sender, EventArgs e)

        {

            string path = Server.MapPath("uploads")+@"\"+FileUpload1.FileName;

            FileUpload1.SaveAs(path);

            Image1.ImageUrl = @"uploads\" + FileUpload1.FileName;

        }

Code in VB.NET:

 

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        Dim path As String = (Server.MapPath("uploads") & "\") + FileUpload1.FileName

        FileUpload1.SaveAs(path)

        Image1.ImageUrl = "uploads\" + FileUpload1.FileName

    End Sub

 

Now save and run the application and click on the browse button to select an image.


 

upload2.gif
 

Figure 2.


 

Now click on the button. Image will be display on the image control.


 

upload3.gif
 


 

Figure 3.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.