Using the file upload in ASP.NET control is easy as ABC but there are times when you will like to validate the file type that is being uploaded and the size of the file remembering the fact that there is a maximum file size allowed in the server's config file.
I will demonstrate with an image upload control (imgUpload) that stores image on a database.
I am trying to ensure that only gif, png or jpg are allowed and maximum size of 300Kb.
if (newFileName.EndsWith(".gif") newFileName.EndsWith(".png") newFileName.EndsWith(".jpg"))
{
#region Image size
if (this.imgUpload.PostedFile.ContentLength < 300000)
{
using (BinaryReader reader = new BinaryReader(imgUpload.PostedFile.InputStream))
{
//Add Image
byte[] img = reader.ReadBytes(imgUpload.PostedFile.ContentLength);
HealthOrganisationImageFacade image = new HealthOrganisationImageFacade();
HealthOrganisationImageDTO pix = new HealthOrganisationImageDTO(0, OrganisationID, img, Organisation.Text, imgUpload.PostedFile.ContentLength, imgUpload.PostedFile.ContentType);
image.AddHealthOrganisationImage(pix);
}
lblWarn.Text = "Image uploaded.";
lblWarn.ForeColor = System.Drawing.Color.Green;
lblWarn.Visible = true;
}
else
{
lblWarn.Text = "Images cannot exceed 350KB.";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
#endregion
}
else
{
lblWarn.Text = "Only extensions .gif, .png, or .jpg are allowed.";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
QED.
I will demonstrate with an image upload control (imgUpload) that stores image on a database.
I am trying to ensure that only gif, png or jpg are allowed and maximum size of 300Kb.
if (newFileName.EndsWith(".gif") newFileName.EndsWith(".png") newFileName.EndsWith(".jpg"))
{
#region Image size
if (this.imgUpload.PostedFile.ContentLength < 300000)
{
using (BinaryReader reader = new BinaryReader(imgUpload.PostedFile.InputStream))
{
//Add Image
byte[] img = reader.ReadBytes(imgUpload.PostedFile.ContentLength);
HealthOrganisationImageFacade image = new HealthOrganisationImageFacade();
HealthOrganisationImageDTO pix = new HealthOrganisationImageDTO(0, OrganisationID, img, Organisation.Text, imgUpload.PostedFile.ContentLength, imgUpload.PostedFile.ContentType);
image.AddHealthOrganisationImage(pix);
}
lblWarn.Text = "Image uploaded.";
lblWarn.ForeColor = System.Drawing.Color.Green;
lblWarn.Visible = true;
}
else
{
lblWarn.Text = "Images cannot exceed 350KB.";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
#endregion
}
else
{
lblWarn.Text = "Only extensions .gif, .png, or .jpg are allowed.";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
QED.
Comments