Validate Image extensions upon Upload

In my previous two examples, we have learned on how to Upload and Save the Image to a Folder and path to database and how to Save the Image to the Database. The two previous examples only tackle the basics about uploading and saving a file without validating the file to be uploaded. In this example, I’m going to show on how to validate a file that only allows image files to be uploaded using server side validations.

Here are the code blocks below:

    private void StartUpLoad()

    {

        if (FileUpload1.HasFile)

        {

            HttpPostedFile postedFile = FileUpload1.PostedFile;

            if (IsImageFile(postedFile))

            {

                //Save image here

            }

            else

            {

                Response.Write("Invalid File, Cannot Upload!");

            }

        }

        else

        {

            Response.Write("Please select a File");

        }

    }

    protected bool IsImageFile(HttpPostedFile file)

    {

        bool isImage = false;

        System.IO.FileStream fs = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

        System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

        string fileclass = "";

        byte buffer;

        try

        {

            buffer = br.ReadByte();

            fileclass = buffer.ToString();

            buffer = br.ReadByte();

            fileclass += buffer.ToString();

        }

        catch

        {

            return false;

        }

        finally

        {

            br.Close();

            fs.Close();

        }

        /*extension lists with codes

         *7173        gif

         *255216      jpg

         *13780       png

         *6677        bmp

         *239187      txt,aspx,asp,sql

         *208207      xls.doc.ppt

         *6063        xml

         *6033        htm,html

         *4742        js

         *8075        xlsx,zip,pptx,mmap,zip

         *8297        rar  

         *01          accdb,mdb

         *7790        exe,dll          

         *64101       bat

         */

        //only allow images    jpg       gif     bmp     png     

        String[] fileType = { "255216", "7173", "6677", "13780" };

        for (int i = 0; i < fileType.Length; i++)

        {

            if (fileclass == fileType[i])

            {

                isImage = true;

                break;

            }

        }

        return isImage;

    }

As you can see, we have checked the posted file of the FileUpload and pass it to the IsImageFile() method that returns a Boolean type for checking the actual type of the posted file. If the file contains image extension such as “jpg”, “gif”, “bmp” and “png” then it will return TRUE else it will return false.

That's it! Hope you will find this example useful!

Technorati Tags: ASP.NET,C#,TipsTricks,Image Uploading

This article is part of the GWB Archives. Original Author: Vincent Maverick Durano

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.