23.11.09

Using FileUpload control in ASP.NET 2.0

The FileUpload control in ASP.NET 2.0 allows users to upload files onto the server. It is a familiar control on social networking sites and signup pages where users are required to upload images as profile photos or album pics. So, how exactly does one code up the process of uploading to the server? Read on.

The FileUpload control in ASP.NET 2.0 uploads the specified file at the specified path on the user's machine to a specified path on the web server. There are two approaches to this:
  1. SaveAs() method

  2. The simpler, zero-effort approach is to use the SaveAs() method of the FileUpload control itself. What you need to do is write this single line of code in the event handler of the Upload button on your WebForm.


    fileupload1.SaveAs(@"Uploads\" + fileupload1.FileName);

    The above code uploads the file to the Uploads folder on the web server.

  3. HttpPostedFile object

  4. The PostedFile property of the FileUpload control returns an HttpPostedFile object which can be used to obtain additional information about the file uploaded such as length in bytes (ContentLength property) and MIME type (ContentType property). It also returns a Stream object through its InputStream property which is exactly the property useful in uploading. Take a look at the code.


    1. HttpPostedFile uploadedFile = fileupload1.PostedFile;

    2. // Read all data from the file into a byte array
    3. int len = uploadedFile.ContentLength;
    4. byte[] data = new byte[len];
    5. uploadedFile.InputStream.Read(data, 0, len);

    6. // Create a new file and stream the bytes to it
    7. FileStream file = new FileStream(Server.MapPath(@"Uploads\" +
    8. fileupload1.FileName, FileMode.Create);
    9. file.Write(data, 0 , len);
    10. file.Close();



    The latter method is the one I invented because I had not known the SaveAs() method of the FileUpload control when I first used it. As for you, the choice is entirely in your hands.