Asp.net Basics : Uploading a file in asp.net using validations (Part 1 of 5)

CoverImageASPNetFileUpload

This is the Part 1 of the 5 part tutorial on how to upload file onto the server using asp.net and validate the file.

File Upload in asp.net : Basics

Following controls are required for uploading a file to server using asp.net

  • File upload control : It will only be used to select file which will be uploaded on server, it will not be used to upload the file.
  • Button : To upload a file we need a button, drag and drop the button on the screen from toolbox and change the button name to “Upload File”.
  • A label control : To display the status of the upload.

File Upload in asp.net : v1.0 (no validations used, the file will be uploaded as it is)

This is the basic form of file upload, where no validations are being used, user can upload as much large file as possible. But one thing must be noted that this method should be strictly avoided as there is no validations used in this method (validations explained in v1.1 and v1.2) and can be a subject to DDoS attacks (Denial of service) and can shut down the server. This code is just to show how to upload a file and save it on server.

Here is the back end structure I am using on Microsoft Visual Studio 2008.

FileUpload4

Here a file upload control is used which is used to select the file and an upload button which will upload the file. The second row will display the characteristics of the file, whether the file is a “.pdf” or a “.doc” (and other extensions) file and display the image of file type. The second row is being hidden with a panel until the file isnt uploaded.

Let us take a “.pdf” file which will be uploaded on the server under the “uploads” folder. The main code used for uploading a file onto server is :-

Complete explanation of the code :-

FileUpload1 : The contol name of the FileUpload in toolbox, administrators can use any file name.

SaveAs : Its the method found in System.Web.UI.WebControls  namespace and in System.Web (System.Web.dll) assembly, its main purpose is to save the file on the server.

MapPath : This method is used to return the complete physical path for the virtual path that you pass in the method.

Now let us upload a file on the server for example “SampleFile.pdf” is being uploaded on the server. The output once the file is uploaded is :-

FileUpload2

The complete cs code for v1.0 is (remember this doesn’t use any validations, only retrieves the name and the file extension of the file) :-

We will discuss about our first validation (empty file validation) in our next tutorial.


Leave a Reply

Your email address will not be published. Required fields are marked *