Microsoft KB Archive/315832

= How to upload an image file to a Web site by using Visual Basic .NET or Visual Basic 2005 =

Article ID: 315832

Article Last Modified on 5/21/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft ASP.NET 1.0

-



This article was previously published under Q315832





For a Microsoft Active Server Pages version of this article, see 299692.



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)  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 tag: EncType=&quot;multipart/form-data&quot; action=&quot;WebForm1.aspx&quot;   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 tags:  </li>  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 tags, after the Input control code: <asp:button id=&quot;btnUpload&quot; type=&quot;submit&quot; text=&quot;Upload&quot; runat=&quot;server&quot;></asp:button> </li>  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 tags, after the Button control code: <asp:Panel ID=&quot;frmConfirmation&quot; Visible=&quot;False&quot; Runat=&quot;server&quot;> <asp:Label id=&quot;lblUploadResult&quot; Runat=&quot;server&quot;/> </asp:Panel> </li> 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.</li>  Add the following the code at top of the code-behind page: Imports System.IO                   </li>  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 = &quot;C:\Temp\&quot; '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 & &quot; already exists on the server!&quot; Else oFile.PostedFile.SaveAs(strFilePath) lblUploadResult.Text = strFileName & &quot; has been successfully uploaded.&quot; End If 'Display the result of the upload. frmConfirmation.Visible = true </li> Click Save.</li> On the Debug menu, click Start to build and run the application. A text box and a command button should appear.</li> Type the path to the image file in the text box, or click Browse to browse to the image file on your local computer.</li> 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.</li></ol>

Complete code listing
<%@ Page Language=&quot;vb&quot; AutoEventWireup=&quot;false&quot; Codebehind=&quot;WebForm1.aspx.vb&quot; Inherits=&quot;WebApplication3.WebForm1&quot;%> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;> <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; content=&quot;Microsoft Visual Studio.NET 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; content=&quot;Visual Basic 7.0&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot; EncType=&quot;multipart/form-data&quot; action=&quot;WebForm1.aspx&quot;> Image file to upload to the server: <INPUT id=&quot;oFile&quot; type=&quot;file&quot; runat=&quot;server&quot; NAME=&quot;oFile&quot;> <asp:button id=&quot;btnUpload&quot; type=&quot;submit&quot; text=&quot;Upload&quot; runat=&quot;server&quot;></asp:button> <asp:Panel ID=&quot;frmConfirmation&quot; Visible=&quot;False&quot; Runat=&quot;server&quot;> <asp:Label id=&quot;lblUploadResult&quot; Runat=&quot;server&quot;></asp:Label> </asp:Panel> </HTML>

Imports System.IO Public Class WebForm1Public Class WebForm1 // Note In Visual Studio 2005, &quot;Public Class WebForm1&quot; should be changed to &quot;Partial Class _Default&quot;. 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


 * 1) Region &quot; Web Form Designer Generated Code &quot;

'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


 * 1) 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 = &quot;C:\Temp\&quot;

'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 & &quot; already exists on the server!&quot; Else oFile.PostedFile.SaveAs(strFilePath) lblUploadResult.Text = strFileName & &quot; has been successfully uploaded.&quot; End If

'Display the result of the upload. frmConfirmation.Visible = True

End Sub End Class

Verify that it works
<ol> Upload a new file to the server. You receive the following message:

<pre class="fixed_text">File name has been successfully uploaded

</li> Upload the same file again. You receive the following message:

<pre class="fixed_text">file name already exists on the server!

</li></ol>

The files that you copy are saved in the :\Temp folder on the local hard disk.