This article will discuss about implementing File Upload extension validation. It is a common mistake that developers used to do when they receive a file upload on the server - they only check the file extension. You will find lot of code like this.
The drawback of this implementation is - you can rename an executable file to
.txt, and your system will accept it. If you’re using ASP.NET - you may say that I am using the
MimeMapping.GetMimeMapping API to get the file content type - but unfortunately this method also returns the content type based on file name. So if you’re using simple extension based checking or you’re using
GetMimeMapping API method - both are not correct approach.
The solution is extract the File Header from the file and compare it with your required file types. Building it from scratch is little complicated. Recently I found a nuget package -
myrmec which helps you to solve this problem. To get started you need to install this package to your application. Next you need to configure a mapping with the required file types. In this demo I am checking for docx, pptx, xlsx, jpg, gif, png and pdf file types. Once it is done you need to extract first 20 bytes of the file content and verify it with
Here is the implementation.
And here is the
In the implementation, the
sniffer.Match API will return a list of content types of the File you’re providing - if it in the list of configured mapping the list contains the content type otherwise it will be empty. In this implementation, I am ignoring the files which is not matching the required file types, you need to write code to inform the user. This way you can implement the server side file type validation in ASP.NET Core MVC. You can find the mapping values from the GitHub page.
Happy Programming :)