Asp Net Source.com
What's ASP.NET?

AspNetSource.com's BLOG

AJAX, ASP.NET, C#, CSS, Design, .NET Framework, Javascript, SQL, VB.NET, etc.

Using ASP.NET FileUpload to work with Images

Posted by Tihomir Ivanov on 08 December 2009 16:57
Rating: 8.00

I'm writing ability user of my site http://www.devtheweb.net to have ability to change their avatar photos by uploading their own image files.

In this article you can find:
- how to check on server-side if file is selected by FileUpload
- how to check on server-side if Image file is selected by FileUpload
- how to check Image dimensions from file selected by FileUpload

In .aspx file we have a FileUpload Control, Button to submit file and a Label to output result in it:

<div>
  <asp:FileUpload ID="_customImageFU" runat="server" />
</div>
<div>
  <asp:Label ID="_resultLbl" runat="server" ForeColor="Red"></asp:Label>
</div>
<div>
  <asp:Button ID="_uploadImageBtn" runat="server" onclick="_uploadImageBtn_Click" Text="Upload" />
</div>

in code-behind file, we handle the Submit Button Click and check for valid image:

protected void _uploadImageBtn_Click(object sender, EventArgs e)
{
      string extension, filename;

      try
     {
           //t checks if file exists
           if (!_customImageFU.HasFile)
          {
               _resultLbl.Text = "Please, Select a File!";
               return;
          }

          //t checks file extension
         extension = System.IO.Path.GetExtension(_customImageFU.FileName).ToLower();

          if (!extension.Equals(".jpg") && !extension.Equals(".jpeg")
              && !extension.Equals(".gif") && !extension.Equals(".png"))
         {
              _resultLbl.Text = "Only image files (.JPGs, .GIFs and .PNGs) are allowed.";
              return;
          }

          //t checks if image dimensions are valid
         if (!ValidateFileDimensions(100, 100))
        {
             _resultLbl.Text = "Maximum allowed dimensions are: width <= 100px and height <= 100px.";
            return;
        }

        filename = Server.MapPath("~/some_folder/") + "some-file-name" + extension;

       _customAvatarFU.SaveAs(filename);
   }
   catch (Exception)
  {
       //t handle the exception
  }
}

public bool ValidateFileDimensions(int aHeight, int aWidth)
{
       using (System.Drawing.Image image = System.Drawing.Image.FromStream(_customImageFU.PostedFile.InputStream))
      {
           return (image.Height <= aHeight && image.Width <= aWidth);
      }
}

That's all :)

 Comments:
us Posted by SQL course on 12 January 2011 21:29   Rating: 8
By using this code, can I upload different picture format?
 
Our Sponsors:  Asp.net file upload component  |   Flash file uploader  |  ASP.NET Hosting