Using Visual Basic .NET to Upload a File to a Web Server in ASP.NET
his 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
- Start Microsoft Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
- 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
- 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.
- To change the folder name to Data, right-click NewFolder1, click Rename, and then type Data.
- 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:
C:\Inetpub\wwwroot\VBNetUpload\Data
- To change the security settings to grant write permissions to the Data directory, right-click Data, and then click Properties.
- In the Data Properties dialog box, click the Security tab, and then click Add.
- 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.
- Click the aspnet_wp account (computername\ASPNET) account, and then click to select the Allow check boxes for the following permissions:
Click to clear any other Allow and Deny check boxes.
- 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
- Return to the open instance of Visual Studio .NET. WebForm1.aspx should be open in the Designer window.
- To view the HTML source of the WebForm1.aspx page, right-click WebForm1.aspx in the Designer window, and then click View HTML Source.
- Locate the following HTML code, which contains the <form> tag:
<form id="Form1" method="post" runat="server">
- Add the enctype="multipart/form-data" name-value attribute to the <form> tag as follows:
<form id="Form1" method="post"
enctype="multipart/form-data" runat="server"> - After the opening <form> tag, add the following code:
<INPUT type=file id=File1 name=File1 runat="server" />
<br>
<input type="submit" id="Submit1" value="Upload"
runat="server" /> - Verify that the HTML <form> tag appears as follows:
<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
- On the View menu, click Design.
- Double-click Upload. Visual Studio opens the WebForm1.aspx.vb code-behind file and automatically generates the following method code:
Private Sub Submit1_ServerClick(ByVal sender _
As System.Object, _
ByVal e As System.EventArgs) _
Handles Submit1.ServerClick
End Sub
- Verify that the following code exists at the class level of the WebForm1.vb file:
- Locate the following code:
Private Sub Submit1_ServerClick(ByVal sender _
As System.Object, _
ByVal e As System.EventArgs) _
Handles Submit1.ServerClick
- Press ENTER to add a blank line, and then add the following code:
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
- Verify that the Submit1 subroutine appears as follows:
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
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
Test the Application
To build your Visual Studio .NET solution and to test the application, follow these steps:
- On the Build menu, click Build Solution.
- In Solution Explorer, right-click WebForm1.aspx, and then click View in Browser.
- After WebForm1.aspx opens in the browser, click Browse.
- In the Choose File dialog box, select a file that is smaller than 4 megabytes (MB), and then click Open.
- 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.
- Return to the open instance of Windows Explorer, and then locate the Data directory.
- Verify that the file has been uploaded to the Data directory.
Upload Larger Files
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.
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"
/>
Complete Code Listing
<%@ 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
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.
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).
No comments:
Post a Comment