File Uploading in ASP.NET Using C#

http://www.stardeveloper.com/articles/display.html?article=2002022201&page=1

File Uploading in ASP.NET Using C#
by Sriram Vaideeswaran.

Overview :
File uploading has always been a tedious task for the web developer community. Either we have to use a third party component or write several lines of code. With the advent of ASP.NET file uploading has become a lot easier, importantly without the need for third party components. All we have to do is to use the ASP.NET HTML File control and write a few lines of C# code.

This article guides you through the file uploading process. In classic ASP we would use the HTML file control for uploading files. In ASP.net we replace this with the ASP.NET HTML File control.The declaration of ASP.NET HTML file control is much like normal HTML file control except for the runat attribute set to server. (e.g)

<input type="file" id="myfile" name="myfile" runat="server" />

Similarly we use the ASP.NET button control which the the user will click to upload the file he has selected using the file control. As ASP.NET follows event based programming model we can attach a server side event which will respond to clicking of the button. This is done by using the OnClick event handler of the button control. To this event we assign the name of the method which we want to be executed on the server when the user clicks the button. (e.g)

<asp:button id="cmdUpload" name="cmdUpload" runat="server" OnClick="UploadFile" />

Now we can write C# code within the UploadFile method to save the uploaded file in the server. This code can be written in two ways depending on the number of file controls we have within the page. If there is only a single file control then we can use the PostedFile property of the file control to upload files. This property is of type HttpPostedFile class and contains the following methods and properties which aids file uploading.

Properties
Property Description
FileName Returns the full path and name of the uploaded file.
ContentType The MIME type of the uploaded file.
ContentLength The size in bytes of the uploaded file.

Method
Methods Description
SaveAs(Path) Saves the uploaded file to the specified path.

If we have multiple file controls within the form we can use the Files property of the Request object which returns a reference to the HttpFileCollection class. HttpFileCollection class has an Item property through which gets individual HttpPostedFile from the file collection either by specifying the name or index.

你可能感兴趣的:(asp.net)