Uploading files to the server
Uploading files to the server is made simple using the FileUpload web server
control.
We first check there is a file to upload by looking at the HasFile property.
We then save the file by calling the FileUpload1.PostedFile.SaveAs method.
We need to supply this method with the fully qualified file name so we need to get
the server name. This is achieved using either Server.MapPath("~/") or HttpContext.Current.Server.MapPath("~/")
which returns the applications root directory path.
Server.MapPath("~/") = "H:\hshome\serverghar1\surecode.net\"
All that's left is to add the location on the server and the files name. The basic
code for uploading a file would be:
if (FileUpload1.HasFile)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/")+"UploadArea/"+FileUpload1.FileName);
}
This would upload the file to a root folder named "UploadArea". Files with the same
name are overwritten.
You can use the control below to view some properties of a selected file. (Note
that no files are uploaded)
FileUpload1 Properties:
FileUpload1.HasFile =
FileUpload1.FileName = "
"
FileUpload1.PostedFile.FileName = "
"
FileUpload1.PostedFile.ContentLength =
The default maximum file size is 4mb although this can be changed within the Web.Config
by setting the MaxRequestLength value. This example would set the maximum upload
file size to 2mb.
<system.web>
<httpRuntime maxRequestLength="2048" />
</system.web>
Full details of the FileUpload control can be found at the Microsoft Website.