how to make sure of the uploaded file type in c#

Viewed 4285

I want to let users upload images and videos to my website. Normally I check the image extension for jpg or png extension. But I tested the security of my web by upload a shell to hack it, so I changed the shell's extension to .jpg.

Sadly it had been uploaded to the host's folder normally and shows all my files, so if any one know the best way to make sure this file is a video or this file is a real image before uploading it to the host in C# Asp.net web forms.

3 Answers

I would like to share the simplest way to get the filetype/ content type before uploading a file.

            string file_type;
            var provider = new FileExtensionContentTypeProvider();
            if(!provider.TryGetContentType(finlename, out file_type))
            {
                file_type = "application/octet-stream";
            }

You can check the content type of the file. The following code might help:

public static readonly string[] mimeTypes = new[] { "image/jpeg", "image/png" };

if (mimeTypes.Contains(fileBox.PostedFile.ContentType))
{ // Do something.    
}

Also, I would suggest client side validation. This will help check the content type before posting to the server. This will also help with saving bandwidth.

Following link should help you:

How to check file MIME type with javascript before upload?

Not only file extension, but checking mime type for "image/jpeg, image/png, image/gif' is the way to go.

You can validate the extension of a file. Using this code.

   protected void ValidateFile(IFormFile file)
    {
        if (file == null)
            throw new Filters.ApiException(this.Localizer[string.Format(ErrorConst.SelectFile)].Value, 400);
        if (file.Length < 1)
            throw new Filters.ApiException(this.Localizer[string.Format(ErrorConst.ErrorImageSize)].Value, 400);

        int filesize = 3;
        string[] supportedTypes = new[] { "jpg", "jpeg", "png", "bmp" };
        var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
        if (!supportedTypes.Contains(fileExt))
            throw new Filters.ApiException(this.Localizer[ErrorConst.ErrorImageExtension].Value, 400);
        if (file.Length > (filesize * 1024 * 1024))
            throw new Filters.ApiException(this.Localizer[string.Format(ErrorConst.ErrorImageSize, filesize)].Value, 400);
    }

And this is validated file and file size.

Thanks.

Related