Upload Files in ASP.NET using VB.NET
How to Upload Files in ASP.NET using VB.NET
ASP.NET 4.0 comes with a FileUpload control that allows you to send a file from your computer to a Web server. The file to be uploaded is submitted to the server as part of the browser request during postback. After the file has completed uploading, you can manage the file in your code.
1. Create an ASP.NET project in Visual Studio 2010.
2. Drag and drop a FileUpload control on Web Form.
3. Write this code on the Page Load event of the Web Form. You need to make sure your folder on the Web Server is set to a valid directory and have write permissions on it.
Protected Sub Page_Load(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim path As String = Server.MapPath("~/UploadFilesFolder/")
Dim fileOK As Boolean = False
If FileUpload1.HasFile Then
Dim fileExtension As String
fileExtension = System.IO.Path. _
GetExtension(FileUpload1.FileName).ToLower()
Dim allowedExtensions As String() = _
{".jpg", ".jpeg", ".png", ".gif"}
For i As Integer = 0 To allowedExtensions.Length - 1
If fileExtension = allowedExtensions(i) Then
fileOK = True
End If
Next
If fileOK Then
Try
FileUpload1.PostedFile.SaveAs(path & _
FileUpload1.FileName)
Label1.Text = "File uploaded!"
Catch ex As Exception
Label1.Text = "File could not be uploaded."
End Try
Else
Label1.Text = "Cannot accept files of this type."
End If
End If
End If
End Sub