Jul 14, 2012

How to upload a file on server using FileUpload control in ASP.NET C#?

//Checking for file is present or not.
if (FileUpload1.HasFile && (FileUpload1.PostedFile != null))
{
    // Validating the size of file.
    if (FileUpload1.PostedFile.ContentLength < (512 * 512))
    {
        if (FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            FileUpload1.PostedFile.ContentType == "application/pdf" || FileUpload1.PostedFile.ContentType == "application/msword")
        {
            try
            {
                // Here Resume is folder in root folder and you have to write permission on this folder to upload files.
                string filePath = "~/Resume/" + Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs(Server.MapPath(filePath));
            }
            catch (Exception ex)
            {
                throw ex;          
            }
        }
        else
        {
            //plz upload only word, excel n pdf. Your error message
            return;
        }
    }
    else
    {
        //Your error message.
        //length of file is bigger than 500kb
        return;
    }
}

No comments: