ASP.NET - image upload control - Asked By Trisha on 12-Jul-12 02:22 AM

Jitendra Faye replied to Trisha on 12-Jul-12 02:30 AM
Use fileUpload control for this-

Try this code-

protected void UploadButton_Click(object sender, EventArgs e)

{

    if(FileUploadControl.HasFile)

    {

      try

      {

        string filename = Path.GetFileName(FileUploadControl.FileName);

        FileUploadControl.SaveAs(Server.MapPath("~/Image/") + filename);

        StatusLabel.Text = "Upload status: File uploaded!";

      }

      catch(Exception ex)

      {

        StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;

      }

    }

}

Hope this will help you,.


Trisha replied to Jitendra Faye on 12-Jul-12 02:41 AM
how to restrict users, so that he can only upload only image files rather than any files..
Jitendra Faye replied to Trisha on 12-Jul-12 03:16 AM
For this you can validate FileUpload control like this-

<script type ="text/javascript">
 
  var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];
 
  function ValidateFile()
 
  {
 
    var file = document.getElementById("<%=FileUpload1.ClientID%>");
 
    var label = document.getElementById("<%=Label1.ClientID%>");
 
    var path = file.value;
 
    var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
 
    var isValidFile = false;
 
    for (var i=0; i<validFilesTypes.length; i++)
 
    {
 
    if (ext==validFilesTypes[i])
 
    {
 
    isValidFile=true;
 
    break;
 
    }
 
    }
 
    if (!isValidFile)
 
    {
 
    label.style.color="red";
 
    label.innerHTML="Invalid File. Please upload a File with" +
 
   " extension:\n\n"+validFilesTypes.join(", ");
 
    }
 
    return isValidFile;
 
   }
 
</script>

Now let us see how to handle this at server side

protected void btnUpload_Click(object sender, EventArgs e)
 
{
 
  string[] validFileTypes={"bmp","gif","png","jpg","jpeg","doc","xls"};
 
  string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName); 
 
  bool isValidFile = false;
 
  for (int i = 0; i < validFileTypes.Length; i++)
 
  {
 
    if (ext == "." + validFileTypes[i] )
 
    {
 
    isValidFile = true;
 
    break;
 
    }
 
  }
 
  if (!isValidFile)
 
  {
 
    Label1.ForeColor = System.Drawing.Color.Red;
 
    Label1.Text = "Invalid File. Please upload a File with extension " +
 
       string.Join(",", validFileTypes);
 
  }
 
  else
 
  {
 
    Label1.ForeColor = System.Drawing.Color.Green;   
 
    Label1.Text = "File uploaded successfully.";
 
  }
 
}