File Upload with VB.NET

Tuesday Jul 17th 2007 by Irina Medvinskaya
Share:

Here is a simple way of providing users with an upload document functionality by using ASP.NET and VB.NET.

Introduction

It has become a popular feature, often expected by users, to allow uploading documents into server-based applications. This is necessary in many applications, from very simple to more complex. In this article, I will show you a simple way of adding a File Upload feature into your ASP.NET applications created with VB.NET. Keep in mind that, although this article provides code samples in VB.NET, you could create the same functionality using C#, if that's your language of choice, by tweaking the code a little bit.

Users of various applications have become more sophisticated in utilizing the web. A number of systems, such as document management systems, content management systems, request management systems, and an array of others would require users to upload documents.

Start Coding

In the example, you will create a simple ASP.NET Web Application that will allow uploading a file to a server.

Open Visual Studio.NET and create a new Project with the following settings:

  • Project Type: Visual C# Projects
  • Templates: ASP.NET Web Application
  • Location: http://localhost/FileUpload

On the web form:

  1. Click on Toolbox, select HTML section, find the File Field control, and drag it onto the form.
  2. Right-click on the control and set "Run as Server Control".
  3. Change the Name property of the control to "File1".
  4. Click on Toolbox again, select Web Forms section, find a Button, and drag it onto the form.
  5. Set its Text property to "Upload" and its ID property to "cmdUpload".

Your screen should resemble this:



Click here for a larger image.

Add the following code to the form definition section of the .aspx file:

encType="multipart/form-data"

As a result, the full form tag would look like this:

<form id="Form1"
      method="post"
      encType="multipart/form-data"
      runat="server">

Add the following code to the declaration section of the .vb file:

Dim sFileDir As String = "C:\"
Dim lMaxFileSize Long = 4096

Keep in mind that the values above will have to be modified to take into the consideration the specifics of your application. You also may make them dynamic and have your application read these values from either a database or an XML file.

Add the following code to very top portion of the .vb page:

Imports System.IO

Add the following procedure .vb code page:

Private Sub DeleteFile(ByVal strFileName As String)

   If strFileName.Trim().Length > 0 Then
      Dim fi As New FileInfo(strFileName)
      If (fi.Exists) Then    'if file exists, delete it
         fi.Delete()
      End If
   End If

End Sub

Add the following code to the .vb file:

Private Sub cmdUpload_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles cmdUpload.Click

'check that the file has been selected and it's a valid file
If (Not File1.PostedFile Is Nothing) _
   And (File1.PostedFile.ContentLength > 0) Then
   'determine file name
   Dim sFileName As String = _
      System.IO.Path.GetFileName(File1.PostedFile.FileName)
   Try
      If File1.PostedFile.ContentLength <= lMaxFileSize Then
         'save file on disk
         File1.PostedFile.SaveAs(sFileDir + sFileName)
         lblMessage.Visible = True
         lblMessage.Text = "File: " + sFileDir + sFileName + _
            " Uploaded Successfully"
      Else    'reject file
         lblMessage.Visible = True
         lblMessage.Text = "File Size if Over the Limit of " + _
            lMaxFileSize
      End If
   Catch exc As Exception    'in case of an error
      lblMessage.Visible = True
      lblMessage.Text = "An Error Occured. Please Try Again!"
      DeleteFile(sFileDir + sFileName)
   End Try
Else
   lblMessage.Visible = True
   lblMessage.Text = "Nothing to upload. Please Try Again!"
End If
End Sub

Press F5 to compile and run the project. Your screen should look like this:



Click here for a larger image.

Click Browse and choose a file to upload. Your screen should look like this:



Click here for a larger image.

Click Upload. You should see a message displayed on top:



Click here for a larger image.

You should check to see whether the file has been copied to the directory specified in the code with its original file name.

How This Works

The values sFileDir and lMaxFileSize have been hard coded at the top and instead can be retrieved from either a database or an XML configuration file. sFileDir specifies the location where on the server the copied file is to be saved. lMaxFileSize specifies the maximum allowed file size for an uploaded file.

The DeleteFile procedure is used to delete the copied file from the server. As a part of the normal cleanup process, after the file upload takes place, the file will be moved either to the database or to some other location on the server depending on the application requirements. In the example, you don't copy the file anywhere so you don't call this procedure unless an error occurs and you need to get rid of the file. DeleteFile can be called after the file has been moved into the database or to another location for cleaning purposes. It accepts a full file name (directory and file name) as one argument and verifies that the file exists and that the length of the argument is bigger than 0. Then, it attempts to delete the file by using the FileInfo object.

When the user clicks cmdUpload, you first check whether such a file exists. If the file exists, you determine the file name without the directory (the File1.PostedFile.FileName property stores the location and the name of the file on the client's computer) by using System.IO.Path.GetFileName. You then verify that the size of the file is not larger than the maximum allowed. After that, you save the file to the designated location on the server by using the File1.PostedFile.SaveAs method and passing the directory and the filename to it. Upon saving the file, you display a message confirming to the user that the file has been uploaded successfully. If an error occurs, you delete the file and display an error message in the lblMessage label.

Note: When uploading files, keep in mind that ASP.NET limits the file size of the uploaded files to 4 MB or 4096 KB. If you try to upload a file that is larger than that, you will get an error. You can change that setting by changing the maxRequestLength setting in the httpRuntime element of the Machine.config file. See Microsoft's web site for more information.

Conclusion

In this sample, you demonstrated a simple way of providing users with an upload document functionality by using ASP.NET and VB.NET.

About the Author

Irina Medvinskaya has been involved in technology since 1996. Throughout her career, she as developed many client/server and web applications, mainly for financial services companies. She works as a Development Manager at Citigroup.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved