WEBSITE

ASP.NET 4 in VB 2010 : Files and Streams - Allowing File Uploads

2/20/2013 8:21:21 PM

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.

Figure 1. A simple file uploader

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.

THE MAXIMUM SIZE OF A FILE UPLOAD

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.
Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone