Although you've seen detailed
examples of how to work with files and directories on the web server,
you haven't yet considered the question of how to allow file uploads.
The problem with file uploading is that you need some way to retrieve
information from the client—and as you already know, all ASP.NET code
executes on the server.
1. The FileUpload Control
Fortunately, ASP.NET includes
a control that allows website users to upload files to the web server.
Once the web server receives the posted file data, it's up to your
application to examine it, ignore it, or save it to a back-end database
or a file on the web server. The FileUpload control does this work, and
it represents the <input type="file"> HTML tag.
Declaring the FileUpload control is easy. It doesn't expose any new properties or events you can use through the control tag:
<asp:FileUpload ID="Uploader" runat="server" />
The <input type="file"> tag doesn't give you
much choice as far as user interface is concerned (it's limited to a
text box that contains a file name and a Browse button). When the user
clicks Browse, the browser presents an Open dialog box and allows the
user to choose a file. This part is hardwired into the browser, and you
can't change this behavior. Once the user selects a file, the file name
is filled into the corresponding text box. However, the file isn't
uploaded yet—that happens later, when the page is posted back. At this
point, all the data from all input controls (including the file data) is
sent to the server. For that reason, it's common to add a button to
post back the page.
To get information about the posted file content, you
can access the FileUpload.PostedFile object. You can save the content
by calling the PostedFile.SaveAs() method:
Uploader.PostedFile.SaveAs("c:\Uploads\newfile")
Figure 1
shows a complete web page that demonstrates how to upload a
user-specified file. This example introduces a twist—it allows the
upload of only those files with the extensions .bmp, .gif, and .jpg.
Here's the code for the upload page:
Public Partial Class UploadFile
Inherits System.Web.UI.Page
Private uploadDirectory As String
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.Load
' Place files in a website subfolder named Uploads.
uploadDirectory = Path.Combine( _
Request.PhysicalApplicationPath, "Uploads")
End Sub
Protected Sub cmdUpload_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdUpload.Click
' Check that a file is actually being submitted.
If Uploader.PostedFile.FileName = "" Then
lblInfo.Text = "No file specified."
Else
' Check the extension.
Dim extension As String = _
Path.GetExtension(Uploader.PostedFile.FileName)
Select Case extension.ToLower()
Case ".bmp", ".gif", ".jpg"
' This is an allowed file type.
Case Else
lblInfo.Text = "This file type is not allowed."
Return
End Select
' Using this code, the saved file will retain its original
' file name when it's placed on the server.
Dim serverFileName As String = _
Path.GetFileName(Uploader.PostedFile.FileName)
Dim fullUploadPath As String = _
Path.Combine(uploadDirectory, serverFileName)
Try
Uploader.PostedFile.SaveAs(fullUploadPath)
lblInfo.Text = "File " & serverFileName
lblInfo.Text &= " uploaded successfully to "
lblInfo.Text &= fullUploadPath
Catch Err As Exception
lblInfo.Text = err.Message
End Try
End If
End Sub
End Class
1.1. Dissecting the Code . . .
The saved file keeps its original
(client-side) name. The code uses the Path.GetFileName() shared method
to transform the fully qualified name provided by
FileUpload.PostedFile.FileName and retrieve just the file, without the
path.
The
FileUpload.PostedFile object contains only a few properties. One
interesting property is ContentLength, which returns the size of the
file in bytes. You could examine this setting and use it to prevent a
user from uploading excessively large files.
By default, ASP.NET will reject a request that's
larger than 4MB. However, you can alter this maximum by modifying the
maxRequestLength setting in the web.config file. This sets the largest
allowed file in kilobytes. The web server will refuse to process larger
requests.
The following sample setting configures the server to accept files up to 8MB:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<!-- Other settings omitted for clarity. -->
<httpRuntime maxRequestLength="8192" />
</system.web>
</configuration>
Be careful, though. When you
allow an 8MB upload, your code won't run until that full request has
been received. This means a malicious server could cripple your server
by sending large request messages to your application. Even if your
application ultimately rejects these messages, the ASP.NET worker
process threads will still be tied up waiting for the requests to
complete. This type of attack is called a denial-of-service attack, and the larger your allowed request size is, the more susceptible your website becomes.