I have an application in which there is a requirement of Uploading csv files.
Everything is working fine. I am uploading files successfully with extension .csv.
Now here is the problem. someone may try to upload exe file by changing its extension to .csv
and upload to server. It is perfectly uploading. Some one suggested me to upload file by using mimetype
. I follow this tutorial.
I am getting mimetype null
for csv files.
So can you please help me how to upload only csv files.
Thanks in Advance
Even if you set the mimetype, I'm guessing that is only determined from the file extension. so setting
.csv
most likely will still bypass it.What I would do is simply read the file for ASCII data if you find anything other than character data throw an error or ignore the file. Loop and compare via numeric range, or you can read it as a string and used a regular expression like
[^\\p{ASCII}]
As far as I know, you can't prevent someone to upload any file type to your server, specially due to the problem you stated like changing the extension. The only possibility you have is to, after receiving the file, try to parse it as a *.csv. If you successfully parse it, you store it in your repository and respond with a success message, if not, you ignore the file and respond with a error message.
Obviously you can parse the csv file client side with Javascript but you should always validate your files server side.
Myme type only tells your server what type to expect, but that won't prevent someone to send you a non csv file.
Well, you are ont he right track. You need to do some kind of file inspection instead of just trusting the file extension.
Either you have to program your own, or use a third party library (which is what you are doing).
If you keep with the third party framework, you must eb having a configuration issue. What the issue is I can't tell from your description, as I don't know the library.
If you are only interested in recognizing CSV files I would recommend something simple that at least you understand and can control. Such as this approach:
Assume that CSV files consist of 0..n lines with the same number of elements pr. line, separated by one of these characters: , ;
It's quite unlikely that an EXE file would have this structure, unless somebody deliberately attack your system with knowledge of your implementation.
Read the first couple of lines.
Split them on the regexp ([,;]).
Check that the results have the same number of elements.
For extra safety, check that they split on the same character.