Using Visual Basic .NET to Upload a File to a Web Server in ASP.NET

Environment: ASP, .NET

This step-by-step article describes how to upload a file to a Web server by using Visual Basic .NET. In this article, you create an ASP.NET file (WebForm1.aspx) and its related code-behind file (WebForm1.aspx.vb) to upload files to a directory that is named Data.

Create the ASP.NET Application

In Microsoft Visual Studio .NET, follow these steps to create a new application to upload files to the Web server:

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Location box, type the URL to create the project. For this example, type http://localhost/VBNetUpload, which creates the default project name of VBNetUpload. Notice that the WebForm1.aspx file loads in the Designer view of Visual Studio .NET.

Create the Data Directory

After you create the application, you create the Data directory that will accept uploaded files. After you create this directory, you must also set write permissions for the ASPNET worker account.

  1. In the Solution Explorer window of Visual Studio .NET, right-click VBNetUpload, point to Add, and then click New Folder. By default, a new folder that is named NewFolder1 is created.
  2. To change the folder name to Data, right-click NewFolder1, click Rename, and then type Data.
  3. Start Windows Explorer, and then locate the Data file system folder that you created in Step 2. By default, this folder is located in the following folder:
  4. C:\Inetpub\wwwroot\VBNetUpload\Data
  5. To change the security settings to grant write permissions to the Data directory, right-click Data, and then click Properties.
  6. In the Data Properties dialog box, click the Security tab, and then click Add.
  7. In the Select Users or Groups dialog box, click the ASPNET account, and then click Add. Click OK to close the Select Users or Groups dialog box.
  8. Click the aspnet_wp account (computername\ASPNET) account, and then click to select the Allow check boxes for the following permissions:
    • Read and Execute
    • List Folder Contents
    • Read
    • Write

    Click to clear any other Allow and Deny check boxes.

  9. Click OK to close the Data Properties dialog box. You have successfully modified the Data directory permissions to accept user-uploaded files.

Modify the WebForm1.aspx Page

To modify the HTML code of the WebForm1.aspx file to permit users to upload files, follow these steps:

  1. Return to the open instance of Visual Studio .NET. WebForm1.aspx should be open in the Designer window.
  2. To view the HTML source of the WebForm1.aspx page, right-click WebForm1.aspx in the Designer window, and then click View HTML Source.
  3. Locate the following HTML code, which contains the <form> tag:
  4. <form id="Form1" method="post" runat="server">
  5. Add the enctype="multipart/form-data" name-value attribute to the <form> tag as follows:
  6. <form id="Form1" method="post"
          enctype="multipart/form-data" runat="server">
    
  7. After the opening <form> tag, add the following code:
  8. <INPUT type=file id=File1 name=File1 runat="server" />
    <br>
    <input type="submit" id="Submit1" value="Upload"
           runat="server" />
    
  9. Verify that the HTML <form> tag appears as follows:
  10. <form id="Form1" method="post" enctype="multipart/form-data"
          runat="server">
    <INPUT type=file id=File1 name=File1 runat="server" />
    <br>
    <input type="submit" id="Submit1" value="Upload"
           runat="server" />
    </form>
    

Add the Upload Code to the WebForm1.aspx.vb Code-Behind File

To modify the WebForm1.aspx.vb code-behind file so that it accepts the uploaded data, follow these steps:

  1. On the View menu, click Design.
  2. Double-click Upload. Visual Studio opens the WebForm1.aspx.vb code-behind file and automatically generates the following method code:
  3. Private Sub Submit1_ServerClick(ByVal sender _
                                    As System.Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Submit1.ServerClick
    
    End Sub
    
  4. Verify that the following code exists at the class level of the WebForm1.vb file:
  5. Protected WithEvents Submit1 _
              As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents File1 _
              As System.Web.UI.HtmlControls.HtmlInputFile
    

    If this code does not exist in the file, add the code into the file after the following line:

    Inherits System.Web.UI.Page
  6. Locate the following code:
  7. Private Sub Submit1_ServerClick(ByVal sender _
                                    As System.Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Submit1.ServerClick
    
  8. Press ENTER to add a blank line, and then add the following code:
  9. If Not File1.PostedFile Is Nothing And _
           File1.PostedFile.ContentLength > 0 Then
    
    Dim fn As String = System.IO.Path.GetFileName(File1. _
                                                  PostedFile. _
                                                  FileName)
    Dim SaveLocation as String = Server.MapPath("Data") & "\" & fn
    Try
      File1.PostedFile.SaveAs(SaveLocation)
      Response.Write("The file has been uploaded.")
    Catch Exc As Exception
      Response.Write("Error: " & Exc.Message)
    End Try
    Else
    Response.Write("Please select a file to upload.")
    End If
    

    This code first verifies that a file has been uploaded. If no file was selected, you receive the "Please select a file to upload" message. If a valid file is uploaded, its file name is extracted by using the System.IO namespace, and its destination is assembled in a SaveAs path. After the final destination is known, the file is saved by using the File1.PostedFile.SaveAs method. Any exception is trapped, and the exception message is displayed on the screen.

  10. Verify that the Submit1 subroutine appears as follows:
  11. Private Sub Submit1_ServerClick(ByVal sender _
                                    As System.Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Submit1.ServerClick
    If Not File1.PostedFile Is Nothing And _
           File1.PostedFile.ContentLength > 0 Then
      Dim fn As String = _
          System.IO.Path.GetFileName(File1.PostedFile.FileName)
      Dim SaveLocation as String = _
          Server.MapPath("Data") & "\" & fn
      Try
        File1.PostedFile.SaveAs(SaveLocation)
        Response.Write("The file has been uploaded.")
      Catch Exc As Exception
        Response.Write("Error: " & Exc.Message)
      End Try
      Else
        Response.Write("Please select a file to upload.")
      End If
    End Sub
    

Test the Application

To build your Visual Studio .NET solution and to test the application, follow these steps:

  1. On the Build menu, click Build Solution.
  2. In Solution Explorer, right-click WebForm1.aspx, and then click View in Browser.
  3. After WebForm1.aspx opens in the browser, click Browse.
  4. In the Choose File dialog box, select a file that is smaller than 4 megabytes (MB), and then click Open.
  5. To upload the file, click Upload. Notice that the file uploads to the Web server and that you receive the "The file has been uploaded" message.
  6. Return to the open instance of Windows Explorer, and then locate the Data directory.
  7. Verify that the file has been uploaded to the Data directory.

Upload Larger Files

By default, ASP.NET permits only files that are 4,096 kilobytes (KB) (or 4 megabytes [MB]) or less to be uploaded to the Web server. To upload larger files, you must change the maxRequestLength parameter of the <httpRuntime> section in the Web.config file.

Note: When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a "Cannot find server or DNS" error message.

If you want to change this setting for all of the computer and not just this ASP.NET application, you must modify the Machine.config file.

By default, the <httpRuntime> element is set to the following parameters in the Machine.config file:

<httpRuntime
executionTimeout="90"
maxRequestLength="4096"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
/>

The Machine.config file is located in the \System Root\Microsoft.NET\Framework\Version Number\Config folder.

Complete Code Listing

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false"
                       Codebehind="WebForm1.aspx.vb"
                       Inherits="VBNetUpload.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR"
          content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name=vs_defaultClientScript content="JavaScript">
    <meta name=vs_targetSchema
          content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">

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

<INPUT type=file id=File1 name=File1 runat="server" >
<br>
<input type="submit" id="Submit1" value="Upload" runat="server"
       NAME="Submit1">


    </form>

  </body>
</HTML>

WebForm1.aspx.vb

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents File1 _
              As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents Submit1 _
              As System.Web.UI.HtmlControls.HtmlInputButton

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form
        'Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                          Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Private Sub Submit1_ServerClick(ByVal sender As System.Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Submit1.ServerClick

        If Not File1.PostedFile Is Nothing And _
               File1.PostedFile.ContentLength > 0 Then
            Dim fn As String = _
               System.IO.Path.GetFileName(File1.PostedFile.FileName)
            Dim SaveLocation as String = Server.MapPath("Data") _
                & "\" & fn
            Try
                File1.PostedFile.SaveAs(SaveLocation)
                Response.Write("The file has been uploaded.")
            Catch Exc As Exception
                Response.Write("Error: " & Exc.Message)
            End Try
        Else
            Response.Write("Please select a file to upload.")
        End If

    End Sub
End Class

More Information

Theoretically, the maximum file upload size is fairly large. However, because of ASP.NET health monitoring, you cannot upload very large files in ASP.NET. The ASP.NET worker process has a virtual address space of 2 gigabytes (GB). However, the ASP.NET worker process only uses a little more than 1 GB because of health monitoring and memory fragmentation.

During the upload process, ASP.NET loads the whole file in memory before the user can save the file to the disk. Therefore, the process may recycle because of the memoryLimit attribute of the processModel tag in the Machine.config file. The memoryLimit attribute specifies the percentage of physical memory that the ASP.NET worker process can exhaust before the process is automatically recycled. Recycling prevents memory leaks from causing ASP.NET to crash or to stop responding.

Additionally, other factors play a role in the maximum file size that can be uploaded. These factors include available memory, available hard disk space, processor speed, and current network traffic. With regular traffic of files being uploaded, Microsoft recommends that you use a maximum file size in the range of 10 to 20 megabytes (MB). If you rarely upload files, the maximum file size may be 100 MB.

Note: You can upload files that are larger than 100 MB in ASP.NET. However, Microsoft recommends that you follow the maximum file upload sizes that are mentioned in this article. To determine more precise file sizes, perform stress testing on computers that are similar to the ones that will be used in production.

You may notice the following error messages if you encounter file size limits during the file upload process:

  • The page cannot be displayed.
  • Server Application is Unavailable

    In the event log, the error message will be similar to the following:

    aspnet_wp.exe (PID:PIDNumber) was recycled because memory
    consumption exceeded the SizeLimit MB (Percentage percent of
    available RAM).
    
  • Exception of type System.OutOfMemoryException was thrown.
  • You may also find that uploads occur very slowly. If you watch the Aspnet_wp.exe process in Windows Task Manager, you will notice that the memory delta changes by 64 KB every 1 to 2 seconds. Depending on the size of the file, this delay may cause the ASP.NET worker process to recycle because of a responseDeadlock error.



Comments

  • Hvad er forskellen mellem øret og øret

    Posted by wanzixiao on 06/03/2013 11:02pm

    [url=http://www.beatsbydrdredanmark.webstarts.com/]Køb høretelefoner billig[/url] Denne nye forretninger med salget af den seneste teknologiske udvikling og kvalitetsudvikling i beats af forskellige mærker er en ganske næring til en. Kompatibilitet er også en grund, der gør folk kører efter de nye versioner på markedet. Beats by Dre er en af de mest populære mærker, når det kommer til hovedtelefoner af højeste kvalitet. News viser, at de har et partnerskab med Apple om at levere et eksklusivt sæt hovedtelefoner der er helt mindre i antal, men ganske højt i prisklasse. Monster beats er også en anden vigtig mærke i serien. [url=http://www.beatsbydrdredanmark.blinkweb.com/]monster beats danmark[/url] Udover alle andre hovedtelefoner par, beats Dre lyd præsentation er temmelig god, ikke som “mudrede” og “uklar” støjende lyde, som ofte er problemer med hver hovedtelefon. Nå, denne genre af hovedtelefon er meget godt for den elektroniske, hård rock, og midt tempo hip-hop musik, som helt sikkert kan rock you ingen tvivl om. billige beats by dre er meget til salg i forskellige musik-butikker og du kan købe dem fra enhver stikkontakt til pluk det til din musik dille. Nå, ingen tvivl om, at du kan have en god musik ved at have det, efter alt dette er ‘beats by Dre «og navnet i sig selv er alt for at angive dets kvalitet. Så ven, så hvis du er en af dem, der søger for at have hovedtelefoner til dit musiksystem eller spekulerer at købe det til din iPhone eller iPod, kan du placere din ordre online. Du kan købe denne genre af hovedtelefoner lige fra sidder fra din hjemmecomputer, logge på hjemmesiden at udforske Dre beats rækkevidde at smage essensen af musikken. [url=http://www.beatsbydrdredanmark.webstarts.com/]beats by dre danmark[/url] Ligegyldigt om nogen efterspørgsel en ny hookup vedrørende personlig ansætte i dit hus samt med henblik på at venstre arm din nuværende lille vedrørende institution, dette er den meget specielle, der vil sikre en favorit BIII øretelefoner spørgende, Min ægtefælle og jeg gravede lidt dybere involveret med det sammen med min ægtefælle og jeg, din ml i allexpect en ny, netop hvad jeg lige kigger ind nedenfor besøgende i de mange standard fornødenheder. Sandheden er, jeg er bare planlægning for dig at adskille idéen sammen i dit tilfælde for at sige det kort sort.

    Reply
  • Uploading folder problem

    Posted by Ramasamy_rams on 08/31/2005 07:39am

    Hello sir, I had a problem in uploading folder & its files I need to upload the whole folder image one by one to my server folder (or) I should save all the file in the client folder to the server database(SQl server 2000 is the database i had image column to save the files).. I need is it possible to do in... ASP.Net with out using web services... or with using web services If we can upload using asp.net can you please send me the code or concept to me. please keep in mind i should save (or) upload all the files in the client folder... Thanks can u tell me how to solve this problem please send the response to ramasamy.p@gmail.com

    Reply
  • hows if download file from other other computer?

    Posted by Legacy on 12/17/2003 12:00am

    Originally posted by: riny

    ok... 
    
    i have seen about upload file how about download file?
    is the logic same with upload file?
    thanks

    Reply
  • Progress Bar?

    Posted by Legacy on 11/17/2003 12:00am

    Originally posted by: Michael Kempe

    Hi!

    Thanks for your advice in using the upload control. My question now is: How can I display a progress bar to the user??? I can't find any source code / examples about it.

    Any idea????

    Thanks in advance!

    Michael

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds