Check Content Type of a file before uploading it to server


Hello readers. Below is the small but an important code to check file contents before uploading to server. There may be a chance that the user want to play with the file upload code. Suppose user want to upload a file, but instead of uploading an image file, he changes the extension of a text file from .txt to .jpg and click on upload,,,,, File uploaded. Because code is checking for extension of uploading file not for the content so he can use the trick to upload an invalid file. To prevent this trick read the code. Code is self explanatory and simple. Just by checking the content type of file. Remember that first check the length of file. If it is greater than than 0 then proceed next, because if you rename a text file .txt to .jpg without writing and text in it, its content type becomes the image content type an user is able to upload a invalid image file of size 0 bytes. After this you can use the rest of code to check maximum file size.

ASPX Page Cdoe

<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fluFile" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </div>
    </form>
</body>
</html>

Code Behind Page Code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string[] types = new[] { "image/pjpeg","image/jpeg", "image/png", "image/gif" };

        if (fluFile.PostedFile.ContentLength > 0)
        {
            if (!types.Contains(fluFile.PostedFile.ContentType.ToString()))
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "<script>alert('Not a image file');</script>");
            }
        }
        else
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "<script>alert('Invalid File..!');</script>");
        }
       
    }
}

Comments

Popular posts from this blog

Get Query String Values With Javascript

Change Css Class of li in ul onclick

Change Text Color with Javascript