server side validation (is it image file or not)

Last post 07-09-2009 4:29 AM by Shengqing Yang - MSFT. 8 replies.

Sort Posts:

  • server side validation (is it image file or not)

    07-02-2009, 4:59 PM
    • Member
      7 point Member
    • aibip
    • Member since 05-05-2009, 5:38 PM
    • Posts 58

    I see many tutorials expainging cliant side validation, but I'm not sure what is the best way to validate image file in server side.

    I have this upload script, but I would like to allow only image files.

    Could you show me how to add validation? (or link to web site )


    Thank you


    If FileField.HasFile Then
                Dim myfilename As String
                Dim strExtension As String
                Dim strTimeStamp As String
                strTimeStamp = DateTime.Now.ToString("yyyyMMddhhmmss")
                myfilename = System.IO.Path.GetFileNameWithoutExtension(FileField.FileName)
                strExtension = System.IO.Path.GetExtension(FileField.FileName)
                Dim fullname As String = myfilename + strTimeStamp + strExtension
               
                Dim originalBMP As New System.Drawing.Bitmap(FileField.FileContent)
                Dim thumbnailSize As Integer = 20
                Dim newWidth As Integer, newHeight As Integer

                If originalBMP.Width > originalBMP.Height Then
                    newWidth = thumbnailSize
                    newHeight = originalBMP.Height * thumbnailSize / originalBMP.Width
                Else
                    newWidth = originalBMP.Width * thumbnailSize / originalBMP.Height
                    newHeight = thumbnailSize
                End If

                Dim newBMP As New System.Drawing.Bitmap(originalBMP, newWidth, newHeight)
                Dim oGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(newBMP)

                oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias
                oGraphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight)
                Try
                    newBMP.Save(Server.MapPath("~/blog/" + fullname))
                    Span1.InnerHtml = "File upload successful."
                Catch ex As Exception
                    Span1.InnerHtml = "There was an error. No file uploaded."
                End Try

                originalBMP.Dispose()
                newBMP.Dispose()
                oGraphics.Dispose()
    End If

  • Re: server side validation (is it image file or not)

    07-03-2009, 12:18 AM
    • All-Star
      91,698 point All-Star
    • vinz
    • Member since 10-05-2007, 11:47 AM
    • Cebu, Philippines
    • Posts 13,769
    • TrustedFriends-MVPs

    aibip:
    I have this upload script, but I would like to allow only image files.

    This may help you:

    http://forums.asp.net/p/1051895/2171502.aspx


    "Code,Beer and Music ~ my way of being a programmer"

  • Re: server side validation (is it image file or not)

    07-03-2009, 12:41 AM

    Hi,

    you can check the file extention on server side.

    If System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".jpg" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".png" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".bmp" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".gif" Then

    End If


    Always "Mark as Answer" the Post That Solves the problem.Because It helps others to find the solution.
    Mohammad Hussain
    http://mohdhussain.blogspot.com/
  • Re: server side validation (is it image file or not)

    07-03-2009, 12:57 AM
    • All-Star
      91,698 point All-Star
    • vinz
    • Member since 10-05-2007, 11:47 AM
    • Cebu, Philippines
    • Posts 13,769
    • TrustedFriends-MVPs

    mohd786hussain:

    you can check the file extention on server side.

    If System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".jpg" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".png" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".bmp" OrElse System.IO.Path.GetExtension(FileField.FullName).ToLower() = ".gif" Then

    End If

    I don't think if this would be a good idea.. what if I rename a word file to image file like x.doc to x.jpg?


    "Code,Beer and Music ~ my way of being a programmer"

  • Re: server side validation (is it image file or not)

    07-03-2009, 1:35 AM

    vinz:
    I don't think if this would be a good idea.. what if I rename a word file to image file like x.doc to x.jpg?

    Hi vinz,

    could you provide me code that can check whether the file is renamed or not as suggested by you above that will be a lot more useful for me.


    Second i think this is the best we can trap whether file uploaded is image fiel or not .



    Always "Mark as Answer" the Post That Solves the problem.Because It helps others to find the solution.
    Mohammad Hussain
    http://mohdhussain.blogspot.com/
  • Re: server side validation (is it image file or not)

    07-05-2009, 2:49 PM
    • Member
      7 point Member
    • aibip
    • Member since 05-05-2009, 5:38 PM
    • Posts 58

    I read the article that vinz posted.

    http://forums.asp.net/p/1051895/2171502.aspx

    Did anyone try "peeking into the stream" method? or Zeerover's method?

    mcmcomasp said there are gliches in the last post...

    What would be the best way?

  • Re: server side validation (is it image file or not)

    07-09-2009, 3:45 AM
    Answer

    aibip:

    I see many tutorials expainging cliant side validation, but I'm not sure what is the best way to validate image file in server side.

    I have this upload script, but I would like to allow only image files.

    Could you show me how to add validation? (or link to web site )

     

    Hi,

    Here is way to detect the real extension of files. Please have a try at the demo below. It runs a function called IsAllowedExtension to judge if the uploaded is an image. Also, it can detect other kinds of files according to the file list in the comments.

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (FileUpload.HasFile)
        {
            HttpPostedFile upFile = FileUpload.PostedFile;
            if (IsAllowedExtension(upFile))
            {
                upFile.SaveAs("path");
            }
        }
    }
    protected bool IsAllowedExtension(HttpPostedFile file)
    {
        bool ret = false;
        System.IO.FileStream fs = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = r.ReadByte();
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();
        }
        catch
        {
            return false;
        }
        r.Close();
        fs.Close();
    
        /*extension list for files
         * 
         *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])
            {
                ret = true;
                break;
            }
        }
        return ret;
    }

    If I have misunderstood you, please feel free to let me know.

    Best Regards,
    Shengqing Yang

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread : )
  • Re: server side validation (is it image file or not)

    07-09-2009, 4:12 AM
    • Contributor
      2,397 point Contributor
    • maverickhyd
    • Member since 03-25-2009, 6:38 AM
    • Posts 416

     Hi Shengqing Yang,

    I have one question

    In sample you are  allow images  with extension of  jpg , gif, bmp, png 

    for example if i am uploading a zip file, in that zip file how can i check weather zip file contains only allowed extensions

    if zip file contains onther than allowed extensions that file is not allowed.

    Thanks in Advance

     

     

     

    Please Mark as Answer if it helped You!
  • Re: server side validation (is it image file or not)

    07-09-2009, 4:29 AM

    maverickhyd:

    for example if i am uploading a zip file, in that zip file how can i check weather zip file contains only allowed extensions

    if zip file contains onther than allowed extensions that file is not allowed.

    Hi,

    As far as I know, to handle such an issue, we can only unzip the zip file and then check files compressed in it one by one.

    Thanks & Regards,
    Shengqing Yang

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread : )
Page 1 of 1 (9 items)