SUMMARY
This article demonstrates how to use the
Input control to upload an image file from a local computer to a Web
site. The file name is validated against the server to ensure that you do not
overwrite an existing file.
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
- Microsoft Visual Basic 2005 or Microsoft Visual Basic .NET
- Microsoft Internet Information Services (IIS) version 5.0
or later
This article assumes that you are familiar with the following topics:
- Web applications
- Microsoft ASP.NET
Use the Input control to upload an image file to a Web site
The
Input control can handle various kinds of input. When you create an
Input control with the Hypertext Markup Language (HTML)
<input type="file"> element, Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET generates a file object, a text box,
and a
Browse button. The user can type a file name in the text box.
Alternately, the user can click
Browse to browse to the local file system and to select a file to
upload.
To create an ASP.NET Web form that includes an input box and
a command button to upload an image file from a local computer to a Web site,
follow these steps:
- Start Visual Studio 2005 or Visual Studio .NET.
- Create a new ASP.NET Web Application project in Visual
Basic .NET.
Note In Visual Studio 2005, you create a Web site. - In the WebForm1.aspx window, switch to HTML
view.
Note In Visual Studio 2005, you switch to HTML
view in the Default.aspx window. - The following code adds the form ENCTYPE attribute to specify the format of the data that is posted. The
browser uses this attribute to properly encode the information that is posted
to the server. The action attribute in this code specifies that the page will process the
request. Finally, the method attribute of the form is set to Post by default so that you can send large amounts of data in the
transaction.
In the HTML window of WebForm1, add the following
attribute/value pairs inside the opening <form> tag:
EncType="multipart/form-data" action="WebForm1.aspx"
- The following code adds the Input control to specify the file that you want to upload to the
server. You can place a text string in front of the control to prompt the
user.
In the HTML window of WebForm1, add the following code between
the opening and closing <form> tags:
<INPUT id="oFile" type="file" runat="server">
- Note that the Input control does not actually upload the file. You must add a Button control to upload the file that you specified in the Input control.
In the HTML window of WebForm1, add the
following code between the opening and closing <form> tags, after the Input control code:
<asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
- The following code displays a message to indicate whether
the file uploads successfully. Create a panel that contains a single label to
display the output.
In the HTML window of WebForm1, add the following
code between the opening and closing <form> tags, after the Button control code:
<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
<asp:Label id="lblUploadResult" Runat="server"/>
</asp:Panel>
- The Visual Basic code retrieves the file from the local
file system, checks to see if the file already exists on the server, and
uploads the file to the Web site.
Switch to Design view for
WebForm1.aspx (click Design in the lower-left corner of the Designer window). Double-click Upload to create an event handler for the Click event of the button. - Add the following the code at top of the code-behind page:
Imports System.IO
- Add the following code to the Click event handler for the command button that you created:
Dim strFileName as string
Dim strFilePath as string
Dim strFolder as string
strFolder = "C:\Temp\"
'Get the name of the file that is posted.
strFileName = oFile.PostedFile.FileName
strFileName = Path.GetFileName(strFileName)
'Create the directory if it does not exist.
If (not Directory.Exists(strFolder)) then
Directory.CreateDirectory(strFolder)
End If
'Save the uploaded file to the server.
strFilePath = strFolder & strFileName
If File.Exists(strFilePath) then
lblUploadResult.Text = strFileName & " already exists on the server!"
Else
oFile.PostedFile.SaveAs(strFilePath)
lblUploadResult.Text = strFileName & " has been successfully uploaded."
End If
'Display the result of the upload.
frmConfirmation.Visible = true
- Click Save.
- On the Debug menu, click Start to build and run the application. A text box and a command button
should appear.
- Type the path to the image file in the text box, or click Browse to browse to the image file on your local computer.
- Click Upload to send the file to the server. If the file is unique, you
receive a message that the upload succeeded. If the file already exists on the
server, you are notified accordingly.
Complete code listing
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication3.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" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">
Image file to upload to the server: <INPUT id="oFile" type="file" runat="server" NAME="oFile">
<asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
<asp:Label id="lblUploadResult" Runat="server"></asp:Label>
</asp:Panel>
</form>
</body>
</HTML>
Imports System.IO
Public Class WebForm1<?xm-insertion_mark_start author="v-xinlw" time="20060113T173801+0800"?>
// Note In Visual Studio 2005, "Public Class WebForm1" should be changed to "Partial Class _Default".<?xm-insertion_mark_end?>
Inherits System.Web.UI.Page
Protected WithEvents btnUpload As System.Web.UI.WebControls.Button
Protected WithEvents lblUploadResult As System.Web.UI.WebControls.Label
Protected WithEvents frmConfirmation As System.Web.UI.WebControls.Panel
Protected WithEvents oFile As System.Web.UI.HtmlControls.HtmlInputFile
#Region " Web Form Designer Generated Code "
'The Web Form Designer requires this call.
<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: The Web Form Designer requires this method call.
'Do not use the code editor to modify it.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Insert user code to initialize the page here.
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnUpload.Click
Dim strFileName As String
Dim strFilePath As String
Dim strFolder As String
strFolder = "C:\Temp\"
'Get the name of the file that is posted.
strFileName = oFile.PostedFile.FileName
strFileName = Path.GetFileName(strFileName)
'Create the directory if it does not exist.
If (Not Directory.Exists(strFolder)) Then
Directory.CreateDirectory(strFolder)
End If
'Save the uploaded file to the server.
strFilePath = strFolder & strFileName
If File.Exists(strFilePath) Then
lblUploadResult.Text = strFileName & " already exists on the server!"
Else
oFile.PostedFile.SaveAs(strFilePath)
lblUploadResult.Text = strFileName & " has been successfully uploaded."
End If
'Display the result of the upload.
frmConfirmation.Visible = True
End Sub
End Class
Verify that it works
- Upload a new file to the server. You receive the following
message:
File name has been successfully uploaded
- Upload the same file again. You receive the following
message:
file name already exists on the server!
The files that you copy are saved in the
Drive:\Temp folder on the local hard
disk.
REFERENCES
For more information, refer to the following Microsoft Developer Network (MSDN) Web sites:
For more information, click the following article number to view the article in the Microsoft Knowledge Base:
295626
Cannot upload large files when you use the HtmlInputFile server control