When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
Technology Jobs
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.
Published: Wednesday, September 12, 2001

Uploading In ASP.NET

By Tribikram Rath


Introduction
With classic ASP, uploading a file from the client to a server required one of three approaches: use of a third-party COM component, use of a custom-written component, or (messy) script code. The easiest option providing the most features was to use a third-party COM component, such as SA-FileUp or ASPUpload. Problems with using the COM model for Web application components are numerous. First off, these components must be registered (generally using the regsvr32.exe tool) before they can be used from a conventional ASP application. Remote administration of these types of applications is not possible, because the registration tool must be run locally on the server. These components remain locked on disk once they are loaded by an application, and the entire Web server must be stopped before these components can be replaced or removed. Furthermore, these third-party COM components cost money. (To learn about the various options for uploading files from the client to the Web server via a classic ASP page, be sure to check out the Uploading Article Index.)

- continued -

'

ASP.NET easily allows developers to provide upload support without the need of any COM component. This is accomplished via the HtmlInputFile class in the .NET Framework. An instance of this class can be created and used easily through an ASP.NET Web page in just a few lines of code. In this article we'll examine how to upload a file from the client to the Web server using ths server control. We'll also examine how to add some extra functionality, such as creating the upload directory, if needed.

Prompting the User to Upload a File
To upload a file from the client to a server in an ASP.NET Web page we need to use a server-side form, but it is very important that this server-side form include the ENCTYPE="Multipart/Form-Data" attribute. Next, you need to create the HtmlInputFile class instance, which you can do using:

<input type="file" id="ID" runat="server" />

The runat="server" is very important, since it informs the ASP.NET engine that the input tag is, in actuality, an Html server control. The resulting Html rendered by this control is simply an input tag with its type set to file. This Html tag has the effect of displaying a textbox with a Browse button next to it. When the user clicks the Browse button, they are displayed a dialog from which they can select a file from their local computer.

So, to recap, the minimal code needed for uploading a file in ASP.NET would be:

<%-- The Web Form with the EncType property set to Multipart/Form-Data --%>
<form Method="Post" EncType="Multipart/Form-Data" RunAt="Server">

   <%-- The File upload Html control --%>
   Choose Your File  To Upload <BR>
   <Input ID="MyFile" Type="File" RunAt="Server">
   <BR>

   <%-- A button - when clicked the form is submitted and the
            Upload_Click event handler is fired... --%>
   <Input Type="Submit" Value="Upload" 
             OnServerClick="Upload_Click" RunAt="Server">

   ...
</form>

The different attributes of HtmlInputFile control could be as follows:

<Input
   Type="File"
   RunAt="Server"
   ID="Specify an ID"
   Accept="Specify MIMEencodings"
   MaxLength="Specify maximum length of file path"
   Size="Specify width of textbox of the control" >

Screenshot of the HtmlFileInput control at work. Note that using the HtmlFileInput Web control creates a textbox with a Browse button. The user can either enter the name of the file in the textbox or click the Browse button and select a file. Once the user has selected a file, the actual file upload does not occur until the Upload button is clicked. Clicking this button has the effect of submitting the form, which fires off the server-side event handler Upload_Click. It is in this event handler that we need to do the actual work of saving the file.

Saving the Uploaded File to the Web Server's File System
When the Upload button is clicked, the form is submitted and the server-side event handler Upload_Click is fired. In this event handler we need to perform the actual task of saving the file to the Web server's file system. This can be accomplished in one line of code. The method MyFile.PostedFile.SaveAs takes a single parameter - the path/filename to save the uploaded file to. (Here, MyFile is the name of the HtmlInputFile control.)

So, before we can save the uploaded file, we must know where to save the file to on the Web server's file system. For this example, let's save it to the C:\ServerFolder\ directory, and let's use the same filename as the uploaded file. To get the name of the uploaded file, we can use the FileName property of the PostedFile object. This property will return the entire filename, though, like C:\SomeClientFolder\Somefile.txt, and we just want to get the filename (just Somefile.txt. We can use the Path.GetFileName method to extract just the filename from the entire path.

Our entire Upload_Click event handler does two simple tasks. First, it extracts the filename of the uploaded file. Next, it saves this file to the C:\ServerFolder\ folder. If an error occurs during this process, an error message is displayed:

Sub Upload_Click(Sender as Object, e as EventArgs)

  ' Display properties of the uploaded file
  FileName.InnerHtml = MyFile.PostedFile.FileName
  FileContent.InnerHtml = MyFile.PostedFile.ContentType 
  FileSize.InnerHtml = MyFile.PostedFile.ContentLength
  UploadDetails.visible = True

  'Grab the file name from its fully qualified path at client 
  Dim strFileName as string = MyFile.PostedFile.FileName
 
  ' only the attched file name not its path
  Dim c as string = System.IO.Path.GetFileName(strFileName)

  'Save uploaded file to server at C:\ServerFolder\
  Try 
    MyFile.PostedFile.SaveAs("C:\ServerFolder\" + c)
    Span1.InnerHtml = "Your File Uploaded Sucessfully at server as: " & _
                      "C:\ServerFolder\" & c
  Catch Exp as exception
    Span1.InnerHtml = "An Error occured. Please check the attached  file"
    UploadDetails.visible = false
    Span2.visible=false
  End Try
End Sub

The Span1, Span2, FileName, FileContent, and FileSize variables in the above event handler refer to label Web controls that we've not examined yet. The purpose of these label Web controls is to provide information about the uploaded file...

Screenshot of a successfully uploaded file When any attempt is made to upload without attaching a file or otherwise, a runtime exception is supposed to be thrown which will be caught by the exception Exp in our Try ... Catch block. As soon as this exception is caught the error message is displayed. The figure to the left shows a screenshot of a successfully uploaded file. Note that the uploaded file's type and size, along with where the file was saved on the Web server's file system, are shown.

Conclusion
There are a few other minor parts to this ASP.NET Web page that we did not explicitly examine in this article. For example, in the Page_Load event handler I have added some code to automatically create the C:\ServerFolder\ folder on the Web server's file system if it does not already exist. Furthermore, we did not touch upon the miscellaneous label controls that display information on the uploaded file. For a more in-depth look at these features, be sure to view the complete source code.

Happy Programming!

  • By Tribikram Rath


    Attachments:

  • View the complete source code (in text format)
  • Visit the Uploading Article Index

  • Software Developer / Programmer - Distributed Systems (NYC)
    Next Step Systems
    US-NY-New York

    Justtechjobs.com Post A Job | Post A Resume


    ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article