ASP.NET 3.5 File Upload Tutorial Using VB.NET

This is a beginner tutorial on designing an ASP.NET web page that will accept file uploads using VB.NET (Visual Basic).

File upload functionally is highly important in a website that accepts files from users. These can be images, music files, etc. The good thing about ASP.NET file upload controls is that you can actually validate user input. For example, you can accept specific file types to be uploaded and restrict others. You can also set a file size upload limit.

These two validation points are important to ascertain that you are receiving and processing the correct file types at acceptable file sizes.

ASP.NET Basic File Upload Form

Let’s try creating a new ASP.NET website project using Visual Web Developer Express and Visual Basic (VB.NET). Name the project "fileupload."

Once the project has been created, you will see the Default.aspx source code. Go to View -> Toolbox -> Standard, and then click and drag the “FileUpload” web control to between:

<form id="form1" runat="server">
<div>

and

</div>
</form>

So it will become:

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
</form>

Bear in mind that a file upload web control will do nothing without some form of an action trigger. In this case, you will need to add a submit button next to the file upload web control.

This submit button, when clicked, triggers a VB.NET script to process the uploaded file, and then save it in a selected destination path in your web server.

In this case, click and drag a Button web control (Toolbox -> Standard -> Button) next to the File Upload web control.  Do not forget to add two break lines (<br /><br />).

The generated markup will be:

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>

This is how it looks in the Design view:

VB.NET script to process file uploads

Since the “submit” button acts as an action trigger, you need to associate it with a click event handler. A click event handler is a VB.NET script that executes when the button is clicked. More details about the click event handler can be found here

In this case, the VB.NET script should do the following tasks:

  1. Import the necessary namespaces required for the classes to work.
  2. Receive the file that is uploaded to the server.
  3. Get the filename of the uploaded file.
  4. Define the path where the file should be uploaded on the server.
  5. Save the file to the uploaded path.

Take the following steps to create the VB.NET script:

1. Go to the Design view of the fileupload project.

2. You need to associate a click event handler with the “Submit” button, so double click the “Submit” button.

3. You will then see the Default.aspx.vb empty script:

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
End Class

4. The following is the complete VB.NET script with comments.

‘Import namespaces for the classes to work

Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Configuration
Imports System.Web.UI
Imports System.Web.Security
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Partial Class _Default
Inherits System.Web.UI.Page

‘Start of the Click event handler function

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

‘Receive the file uploaded from the web form and assign to filereceived variable.

Dim filereceived As String = FileUpload1.PostedFile.FileName

‘Get the file name of the received uploaded file.

Dim filename As String = Path.GetFileName(filereceived)

‘Define the path where the file will be saved in the web server.
‘Since this example takes place in the local host server using Visual Web Developer Express, then local Windows path is used.

Dim fileuploadpath As String = "E:aspdotnetprojectsfileuploadupload"

‘Finally save the uploaded file to the defined upload path.

FileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath, filename))

End Sub
End Class       
       


Since the uploaded file will be saved to the “upload” folder in the fileupload ASP.NET project, you need to create a folder named “upload” in your fileupload project folder.

This is how your project folder will look after adding the upload folder:

{mospagebreak title=Basic Testing of the File Upload Project}

Let’s test the project using a web browser; we’ll try uploading a test file. Go to File -> View in Browser. Try uploading the following sets of files, one at a time:

  • A .jpg file of less than 100 KB in file size.
  • A notepad text file (with a .txt extension) of less than 100 KB in file size.
  • An MP3 file of more than 5 MB in file size.

The following are the observations and the shortcomings of the basic upload file project:

First, you might notice that the first two files listed above were successfully uploaded without any errors, and you can find them in the /upload/ folder of your website. However, when you upload the MP3 file, which is a large file, you encounter the message “Internet Explorer cannot display the web page” if you are developing using IE.

This is because the MP3 file uploaded is beyond the default file size limit, which is 4 MB.

Second, the file upload web form will accept any type of file. In most ASP.NET web applications, only specific file types are needed; so, for security reasons, you will not be accepting files of different types.

Adjusting the Maximum File Size Upload Limit using Web.Config

Suppose you want to increase the file size upload limit to 20 MB. You can specify this in the web.config file by adding the line:

<httpRuntime executionTimeout="110" maxRequestLength="20000" />

Somewhere in between <system.web> and </system.web>.

However, the best practice would be to specify on which ASP.NET web page to impose the file size upload limit for security reasons. In actual implementations, there can be many web pages in your website that accept file uploads; failing to assign a specific file size upload limit can lead to abuse, such as denial of service attacks.

To impose a specific limit for a certain ASP.NET web page, you need to specify it using location path:

<location path="default.aspx">
<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="20000" />
</system.web>
</location>

The above example increases the upload limit to 20 MB only on default.aspx, which is the file name of the ASP.NET web page in this example. You will then place the above code just above the original <system.web> syntax. Screen shot below:

Specific File Type Validation in the File Upload Web Form

To allow only a specific file type to be uploaded (for example, only the MP3 file type), you need to validate user inputs by following the steps listed below.

Step 1. Go to the Default.aspx source code. Paste the validation code below right next to <asp:FileUpload web control:

<asp:RegularExpressionValidator ID="FileTypeValidator" runat="server" ErrorMessage="File type not allowed: Accept MP3 file type only" ValidationExpression="^.+.((mp3))$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>

So after pasting in this code, it will look like this:

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:RegularExpressionValidator ID="FileTypeValidator" runat="server" ErrorMessage="File type not allowed: Accept MP3 file type only" ValidationExpression="^.+.((mp3))$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>

Just change the ValidationExpression to any file type you need, other than MP3, for your own web application.

Step 2. Since the first step performs client side validation, you also need to do server side validation using the Page.IsValid property. This property returns TRUE if the page has been successfully validated.

If a user tries to bypass client validation, the Page.IsValid is FALSE, hence the script will not execute. This property ensures that the page is thoroughly validated before processing the rest of the scripts.

Final VB.NET script with Page.IsValid

Below is the final VB.NET script with the Page.IsValid property. This is similar to the previously shown code:

Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Configuration
Imports System.Web.UI
Imports System.Web.Security
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Partial Class _Default

Inherits System.Web.UI.Page

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

If Page.IsValid Then

‘If the Default.aspx validation is true (for example if the uploaded file is of correct file type, then process the rest of the script.

Dim filereceived As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filereceived)
Dim fileuploadpath As String = "E:aspdotnetprojectsfileuploadupload"         FileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath, filename))
End If
End Sub
End Class


Test it again using a web browser. Try uploading a non-MP3 file; you will see a validation error such as the one shown below:

And when you try uploading an MP3 file which is greater than 4 MB, it will now be successfully uploaded and saved in the /upload/ folder of your website.

You can download the complete project source code here: http://www.dotnetdevelopment.net/tutorials/fileupload.zip

To implement:

  1. Specify your own file type to restrict the validation expression at Default.aspx.
  2. Specify the file size to limit during upload in web.config.
  3. Define your own server path (e.g change the line E:aspdotnetprojectsfileuploadupload, to reflect your own web server path in Default.aspx.vb.).
[gp-comments width="770" linklove="off" ]