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:
- SaveAs() method
- HttpPostedFile object
- HttpPostedFile uploadedFile = fileupload1.PostedFile;
- // Read all data from the file into a byte array
- int len = uploadedFile.ContentLength;
- byte[] data = new byte[len];
- uploadedFile.InputStream.Read(data, 0, len);
- // Create a new file and stream the bytes to it
- FileStream file = new FileStream(Server.MapPath(@"Uploads\" +
- fileupload1.FileName, FileMode.Create);
- file.Write(data, 0 , len);
- file.Close();
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.
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.
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.