ASP.NET File Uploading
Pages: 1, 2
Uploading A File
The code in Listing 3 demonstrates a Web form that is enabled to upload a file. The user interface contains the following controls:
- A
System.Web.UI.HtmlControls.HtmlInputFilecontrol nameduploadedFilefor selecting a file to upload. - A button control for clicking to submit the upload.
- A label control used to display a message from the server (either an error message, if the upload fails, or file information, if the upload succeeds).
Listing 3. Uploading a file
<%@ Import namespace="System.IO"%>
<html>
<head>
<title>Uploading a File</title>
<script language="VB" runat="server">
Dim savePath As String = "C:\temp\"
Sub Upload_Click(source As Object, e As EventArgs)
If Not (uploadedFile.PostedFile Is Nothing) Then
Try
Dim postedFile = uploadedFile.PostedFile
Dim filename As String = Path.GetFileName(postedFile.FileName)
Dim contentType As String = postedFile.ContentType
Dim contentLength As Integer = postedFile.ContentLength
postedFile.SaveAs(savePath & filename)
message.Text = postedFile.Filename & " uploaded" & _
"<br>content type: " & contentType & _
"<br>content length: " & contentLength.ToString()
Catch exc As Exception
message.Text = "Failed uploading file"
End Try
End If
End Sub
</script>
</head>
<body>
<form enctype="multipart/form-data" runat="server">
Select File to Upload:
<input id="uploadedFile" type="file" runat="server">
<p>
<input type=button id="upload"
value="Upload"
OnServerClick="Upload_Click"
runat="server">
<p>
<asp:Label id="message" runat="server"/>
</form>
</body>
</html>
The code in the Web form in Listing 3 has one event handler, Upload_Click, which is triggered when the user clicks the "Upload" button. The Upload_Click event handler first makes sure that the PostedFile property of the HtmlInputFile is not Nothing and obtains the filename, content type, and the content length.
Dim postedFile = uploadedFile.PostedFile
Dim filename As String = Path.GetFileName(postedFile.FileName)
Dim contentType As String = postedFile.ContentType
Dim contentLength As Integer = postedFile.ContentLength
The file is then saved in the specified save path and the filename, content type, and content length of the file are displayed in the message label control.
postedFile.SaveAs(savePath & filename)
message.Text = postedFile.Filename & " uploaded" & _
"<br>content type: " & contentType & _
"<br>content length: " & contentLength.ToString()
ASP.NET File Management
Based on the theory presented in the first two sections of this article, here is a useful application that you can use to manage files on a Web server. This application lets users navigate to the specified root folder and any subfolders under it, and upload or download files from/to those folders. (See Figure 1)

Figure 1. ASP.NET file management
To run the application, you need two pages: the Web form given in Listing 4, and the file download code given in Listing 2. You also need four image files that should be placed in the images subdirectory under the application directory:
- OpenFolder.gif: represents the current directory.
- Folder.gif: represents a subdirectory.
- File.gif: represents a file.
- Up.gif: represents the action of moving up a level in the hierarchy
Listing 4. ASP.NET File Management
<%@ Import Namespace="System.IO"%>
<html>
<head>
<title>File Management</title>
<script language="VB" runat="server">
Dim currentDir As String
Dim directorySeparatorChar As Char = Path.DirectorySeparatorChar
Sub Page_Load(sender As Object, e As EventArgs)
Dim root As String = "C:\temp"
Dim thisPage As String = Request.Path
currentDir = Request.Params("dir")
If currentDir Is Nothing Then
currentDir = root
End If
If Not currentDir.StartsWith(root) Then
currentDir = root
End If
Dim sb As New StringBuilder(4096)
If Not currentDir.Equals(Root) Then
' not at the root
Dim currentDirParent As String
Dim lastIndex As Integer = _
currentDir.LastIndexOf(directorySeparatorChar)
If lastIndex <> -1 Then
currentDirParent = currentDir.Substring(0, lastIndex)
Else
currentDirParent = currentDir
End If
sb.Append("<a href=").Append(thisPage)
sb.Append("?dir=").Append(Server.UrlEncode(currentDirParent))
sb.Append("><img width=30 border=0 src=images/Up.gif></a><br>")
End If
DoUpload()
sb.Append("<br><img border=0 src=images/OpenFolder.gif> ")
sb.Append("<font face=verdana>")
sb.Append(currentDir)
sb.Append("</font>")
sb.Append("<br>")
sb.Append("<table>")
sb.Append("<tr bgcolor=#D8D8D8>")
sb.Append("<td width=200><font face=verdana size=3>Name</font></td>")
sb.Append("<td><font face=verdana size=3>Type</font></td>")
sb.Append("<td><font face=verdana size=3>Size</font></td>")
sb.Append("<td><font face=verdana size=3>Modified</font></td>")
sb.Append("</tr>")
Dim dirs() As String
Try
dirs = Directory.GetDirectories(currentDir)
Dim d As String
For Each d In dirs
Dim dirName As String = Path.GetFileName(d)
sb.Append("<tr>")
sb.Append("<td><img src=images/Folder.gif> ")
sb.Append("<a href=").Append(thisPage)
sb.Append("?dir=").Append(Server.UrlEncode(currentDir))
sb.Append(directorySeparatorChar)
sb.Append(Server.UrlEncode(dirName))
sb.Append(">").Append(dirName).Append("</a>")
sb.Append("</td>")
sb.Append("<td><font face=verdana size=2>folder</font></td>")
sb.Append("<td> </td>")
sb.Append("<td><font face=verdana size=2>")
sb.Append(Directory.GetLastWriteTime(currentDir & _
directorySeparatorChar.ToString() & dirName).ToString())
sb.Append("</font></td>")
sb.Append("</tr>")
Next
Catch ex As Exception
End Try
Try
Dim dirInfo As New DirectoryInfo(currentDir)
Dim files() As FileInfo
files = dirInfo.GetFiles()
Dim f As FileInfo
For Each f In files
Dim filename As String = f.Name
sb.Append("<tr>")
sb.Append("<td><img src=images/File.gif> ")
sb.Append("<a href=FileDownload.aspx?file=")
sb.Append(Server.UrlEncode(currentDir))
sb.Append(directorySeparatorChar)
sb.Append(Server.UrlEncode(filename))
sb.Append(">").Append(filename).Append("</a>")
sb.Append("</td>")
sb.Append("<td><font face=verdana size=2>file</font></td>")
sb.Append("<td><font face=verdana size=2>")
sb.Append(f.Length.ToString())
sb.Append("</font></td>")
sb.Append("<td><font face=verdana size=2>")
sb.Append(File.GetLastWriteTime(currentDir & _
directorySeparatorChar.ToString() & f.Name).ToString())
sb.Append("</font></td>")
sb.Append("</tr>")
Next
Catch ex As Exception
End Try
sb.Append("</table>")
dirContent.Text = sb.ToString()
End Sub
Sub DoUpload()
If Not (uploadedFile.PostedFile Is Nothing) Then
Try
Dim postedFile = uploadedFile.PostedFile
Dim filename As String = Path.GetFileName(postedFile.FileName)
Dim contentType As String = postedFile.ContentType
Dim contentLength As Integer = postedFile.ContentLength
postedFile.SaveAs(currentDir & _
directorySeparatorChar.ToString() & filename)
Catch ex As Exception
message.Text = "Failed uploading file"
End Try
End If
End Sub
</script>
</head>
<body>
<form runat="server" enctype="multipart/form-data" >
<asp:Label id="dirContent" runat="server"/>
<asp:Label id="message" runat="server"/>
<p>
<hr>
<%-- File Upload --%>
<font face=verdana>Select File to Upload:</font>
<input id="uploadedFile" type="file" runat="server">
<input type=button id="upload"
value="Upload"
OnServerClick="Page_Load"
runat="server">
<p>
</form>
</body>
</html>
Summary
File upload is much simpler in ASP.NET than in classic ASP. The first section of this article explained how to write code to upload a file, and the second section discussed programmable file download. The knowledge that you gain from the first two sections is then used in the ASP.NET file management utility offered in Listing 4 of this article.
Budi Kurniawan is a senior J2EE architect and author.
Return to the .NET DevCenter.

