I have worked on many web apps that allow a person to upload and display images (like profile images, background image, etc). A problem I have come across is that you usually provide specific formats that the user can use (i.e jpg, png, jpeg, gif, etc).
Problem is, that suppose you have a profile picture, some may upload a jpeg, some png, and some gif. What format should you save the file in? i.e ‘profile.jpeg‘, ‘profile.png‘ or simply ‘profile‘.
I noticed that you can simply exclude the file extension and the browser opens the image, but is this safe?
The file extension does not determine the file format. You can upload a .gif that ends in a .png and the browser will display it with no difficulties. (You can also use .exe or .foo or whatever, and the image will still display.)
In other words, the extension has nothing to do with security.
On the other hand, I’m not aware of any security risks in passing an unknown file to the browser to display as an image. If you have
<img src="virus.exe">, the browser will do nothing because the file is not a valid image file.If you want to be sure, you could check on the server that the uploaded file is a valid image and discard if it’s not.