Search This Blog

Monday, January 5, 2009

ASP.NET Tutorial - Uploading and Deleting Files via Form in ASP.NET and VB

This tutorial will show how we can upload files to a web server and also use a GridView control to delete files as well. 

Quite often, we want to allow uploading of files to a web server, which enables new content to be loaded much quicker & easier than using FTP. ASP.NET makes this easy for us to do, but what happens when we want to delete files from a web server, too? Well ASP.NET, of course, has an answer for this too. We can use a GridView to display files in a certain directory, and allow a user to delete these files.
First, we need the following assembly reference:

Imports System.IO

We need to add a FileUpload control and a GridView:

" OnRowDeleting="GridView1_RowDeleting" AutoGenerateColumns="False" >

NavigateUrl='<%# "media/ul/" + Container.DataItem.ToString() %>' 
Text='<%# Container.DataItem.ToString() %>'
runat="server" Target="_blank" />

OnClientClick='return confirm("Are you sure you want to delete this entry?");'
Text="Delete?" />

The code-behind will look something like this: 

Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page

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

End Sub

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
If (Not IsPostBack) Then
End If
End Sub

Protected Function GetUploadList() As String()
Dim folder As String = Server.mapPath("/media/ul")
Dim files() As String = Directory.GetFiles(folder)
Dim fileNames(files.Length - 1) As String

For i As Integer = 0 To files.Length - 1
fileNames(i) = Path.GetFileName(files(i))
Next i

Return fileNames
End Function

Protected Sub UploadThisFile(ByVal upload As FileUpload)
If upload.HasFile Then
Dim theFileName As String = Path.Combine(Server.mapPath("/media/ul"), upload.FileName)
labelStatus.Text = "File has been uploaded."
End If
End Sub

Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
e.Cancel = True
Dim fileName As String = (CType(GridView1.Rows(e.RowIndex).FindControl("FileLink"), HyperLink)).Text

fileName = Path.Combine(Server.MapPath("/media/ul"), fileName)
End Sub

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

No comments: