How to check Upload file is real Image file or not in ASP.NET?
In this article I have explained about how to check whether uploaded file is real expected file format (jpg/doc etc.) or not. Here we have checked the uploaded file content first few bytes before upload that file into server database. If not match first few bytes then show error message not a valid file. Find code to check Upload file is real Image file or not in ASP.NET?
Learn how to check Upload file is real Image file or not in ASP.NET?
Description
For example we are allowed to upload only image file in our webpage. Sometimes user renamed .exe file into .jpg file and upload in to our server. It will crash our server if user sends some virus .exe files. So before upload we need to check that files.
First I was checked using FileUpload1.PostedFile.ContentType It will return file type is image or not. For example if user renamed .exe file as .jpg then FileUpload1.PostedFile.ContentType is return other file format so we have show error message. This validation support only in "IE" browser i.e. in other browsers that PostedFile.ContentType return as image only even if you renamed .exe in to .jpg
I found starting bytes of each file types (except txt) files is same. So I have compare that bytes with uploaded file bytes. If user renamed .exe file into .jpg file type, that bytes not match with real image bytes so we can easily detect that file is not valid file. It supports in all browser too.
Check below to know starting bytes for each files
//.JPG file starting bytes like this {255,216,255,224}
//.BMP file starting bytes like this {66,77} First two bytes only equal from third bytes bytes are different for each picture
//.GIF file starting bytes like this {71,73,70,56}
//.PNG file starting bytes like this {137,80,78,71}
//.DOC file starting bytes like this {208,207,17,224}
//.DOCX file starting bytes like this {80,75,3,4}
For example If user upload renamed .exe to .jpg file then that file starting bytes not match with the above real image bytes {255, 216, 255, 224}.
During upload time we check like thisComplete code
Table Structure
CREATE TABLE IMGUPLOAD(ID INT IDENTITY(1,1), IMAGECONTENT IMAGE)
Client Side
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="600">
<tr>
<td height="30" colspan="2">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<td height="30" colspan="2">
<b>PEDF Upload Retrieve Example</b>
</td>
</tr>
<tr>
<td height="30">
Select Your PDF File
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
</tr>
<tr>
<td height="30" colspan="2" align="center">
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Server Side
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
byte[] imgfile;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (checkRealFile(FileUpload1) == true)
{
//valid file save file code write here
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("insert into IMGUPLOAD values (@imgcont)", sqlcon);
sqlcmd.Parameters.Add("@imgcont", imgfile);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Label1.Text = "Successfully Image upload to SQL Server database.";
}
else
{
Response.Write("Not a Valid Image file!");
}
}
}
Boolean checkRealFile(FileUpload passfile)
{
Stream fs = default(Stream);
fs = passfile.PostedFile.InputStream;
BinaryReader br1 = new BinaryReader(fs);
imgfile = br1.ReadBytes(FileUpload1.PostedFile.ContentLength);
//Image file Starting Bytes
byte[] chkByte = { 255, 216, 255, 224 };
//if you want check doc format Content the Use below suitable one for your requirement
//doc files start like this value
//byte[] chkByte = { 208, 207, 17, 224 }; //2003 MS word starting bytes (.doc format)
// byte[] chkByte = {80,75,3,4,20}; //2007 MS word starting bytes (.docx format)
int j = 0;
//Check bytes are equal to real file bytes
for (Int32 i = 0; i <= 2; i++)
{
if (imgfile[i] == chkByte[i])
{
j = j + 1;
if (j == 3)
{
return true;
}
}
else
{
return false;
}
}
return false;
}
}
Source code :
Download the attached source code and try to upload renamed .exe or any other file type into .jpg and upload to SQL Server database
Front End: ASP.NET
Code Behind: C#
Conclusion:
I hope this article is help to know about how to check uploaded file content is real image or not using bytes comparison.
How to check Upload file is real PDFfile or not in ASP.NET?