So, i am developing simple web application using Spring Framework.
The application users can upload images.
What is best practices for storing/loading images?
I found solution on some forum, where someone suggested to store files to user.dir directory.
Ok, i also do that.
When user upload image i store the image to user.dir directory.
Now, i have a question: how to load image from user.dir directory to page?
<img src="path/to/dir/where/images/stored"/>
Best practice is indeed to store such data outside the webapp’s tree to avoid issues on redeployment. Where exactly they get stored is more a matter of convention, user.dir can indeed be a reasonable choice.
You can’t serve these files directly though, commonly it’s done by creating a servlet mapped to eg
images/*that parse the request URL (eg<img src="approot/images/apic.jpg"/>) and based on that url if fetches and servespath/to/dir/where/images/stored/apic.jpg. As an added bonus that servlet gives you full control over what gets downloaded, when and by who, maybe you will need this kind of control later on in the application lifecycle.You can use getPathInfo to retrieve the part of the URL following the servlet name, set the correct MIME type for the output, and streamcopy the requested file to the servlet’s output.
A publicly available, well explained example of such a servlet can be found on BalusC’s blog