This Program explains how to create a file-upload user control in ASP.NET. This will show how to save the uploaded file to disk without granting anonymous users file-write access to folders on your Web server. Finally, you’ll wrap all this in a new ASP.NET user control. This will allow you to add file upload capabilities to almost any Web page quickly and easily.
The .NET Framework offers the FileUpload control to simplify uploading files from web pages.
For this example, we will need to first import the System.Web.UI.WebControls namespace. The System.Web.UI.WebControls namespace contains the classes we need to extract the filename of the file we wish to upload.
1.Create a New Website in asp.net prepared language C#.
2.Add Controls to the Design page.
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.
|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.|
|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.
Finally, you need to add the event handler for the button click. This is the code that does the actual uploading of the file. Actually, there is very little code needed to do this. I
This line uses the name of the control (filename) and accesses the PostedFile object’s SaveAs method to pass the path and filename of the file to save. However, to make the control a bit more robust, you’ll add some server-side content checking and then some code to pull the actual file size, type, and location from the PostedFile object. Finally, you’ll wrap the call to the SaveAs method in a try…catch block and display an appropriate status message based on the results.Add the given code to Button1_Click method referred to in the OnServerClick attribute of the button control. Below is the complete code block for the event handler.
When you actually run the test page you can select a file, set the “SaveAs” name, and press the button to send the file to the server. If you’re successful, you’ll see a message like the one in the screenshot below.