Tuesday, March 4, 2014

File uploading in ASP.NET using C# with file checking

File uploading is an important thing for any kind of websites, and in this post I will show you how to upload a file from your website to server using C#.

For this you need to add a control called FileUploder and a button. So take a web form and add a file uploader control with a button. For uploading files you need to use a method named  FileUpload.SaveAs. Here using this method upload the file into the desire path in the server.




After adding this create a folder where user's uploaded data will be stored. Named it "img" and suppose you will give permission to upload the png files and image size will be less than a certain amount, so for that you need to check two things.
  1. Image type 
  2. Image size

Lets check the code here.
File upload code on Upload Button_Click event.


if (FileUpload1.HasFile)
        {
            if (System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".png")
            {
                if (FileUpload1.PostedFile.ContentLength <= 2100000) /* for upload file limit of 2MB */
                {
                    string FileName;
                    FileName = FileUpload1.FileName.ToString();
                    string UploadFolderPath = "~/img/" + FileName;
                    string FilePath = HttpContext.Current.Server.MapPath(UploadFolderPath);
                    //FileUpload1.SaveAs(FilePath+"//"+FileName);
                    FileUpload1.SaveAs(FilePath);
                    Image1.ImageUrl = "~/img/" + FileUpload1.FileName.ToString();
Response.Write("<script>alert('File uploaded !');<script>");
                }
                else
                {
                    Response.Write("<script>alert('Out of size !');<script>");
                }
            }
            else
            {
                Response.Write("<script>alert('Select .PNG file !');<script>");
            }
        }
        else
        {
            Response.Write("<script>alert('No file selectd !');<script>");
        }

Enjoy the code..

Download Now

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews