Friday, 25 November 2016

How to Upload a file using VB.NET

Hi All,

It is very important to upload file to specific folders in Server.
At first you design one page with a FileUpload control, Label Control and Button Control as given below

Main.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Main.aspx.vb" Inherits="Main" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Welcome to Admin Home
    </div>

 
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Upload" />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    </form>
</body>
</html>

---------------------------------------------------------------------------------------------------------------------
As a next step click the Button Control and add the code in the Main.aspx.vb file

Main.aspx.vb


Partial Class Main
    Inherits System.Web.UI.Page

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

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If FileUpload1.HasFile Then
            Try
                FileUpload1.SaveAs("C:\HUPUploads\" & _
                    FileUpload1.FileName)
                Label1.Text = "File name: " & _
                    FileUpload1.PostedFile.FileName & "<br>" & _
                    "File Size: " & _
                    FileUpload1.PostedFile.ContentLength & "<br>" & _
                    "Content type: " & _
                    FileUpload1.PostedFile.ContentType & "<br>" & _
                    "Location Saved: C:\Uploads\" & _
                    FileUpload1.FileName
            Catch ex As Exception
                Label1.Text = "ERROR: " & ex.Message.ToString()
            End Try
        Else
            Label1.Text = "You have not specified a file."
        End If
    End Sub
End Class


---------------------------------------------------------------------------------------------------------------------
NB: Make sure that you have a folder in C drive as "HUPUploads"




No comments:

Post a Comment