Sunday, October 22, 2006

Uploading files to your website

ASP.NET2.0 introduces a new file upload control!!!

<asp:fileupload id="FileUpload1" runat="server"></asp:fileupload>



The new control exists under the standard tab





Dragging this form appears as follows on the form designer






The properties of this new control is listed below




The actual work is done by some simple lines of C# code, it assumes that there is an uploads folder with the correct permissions to write files into!


String savePath = Request.PhysicalApplicationPath;
savePath += "uploads\";

if(FileUpload1.HasFile()){
--savePath += FileUpload1.FileName;
--FileUpload1.SaveAs(savePath);
}


Please note that SaveAs will cause an existing file with the same name to be overwritten.

Programatially we can limit the size of an upload by doing the following:

if(FileUpload1.PostedFile.ContentLength <= 3145728){
---- //save file
} else {
---- //cancel upload as its greater than 3mb
}

No comments: