Monday, July 21, 2014

Spring MVC serving images from physical file system

Spring MVC serving images from physical file system

Very offen people are in quest of a good solution to store and potray user images viz. personal images, signatures etc and like many people I found myself as one looking out for this kinda solution googling, binging all around internet with almost no notion.

Well, but "Ever tried. Ever failed. No matter. Try Again. Fail again. Fail better."
One nice morning I was able to find a solution for this using Java Spring.

Spring gives you a very nice way to handle how you would display images which are stored somewhere outside your web server/servlet container sandbox.

This tutorial will explain how you should configure your Spring MVC application if you want to serve resources that reside outside the webapp directory, or even outside the whole project archive. In short, how to access files from anywhere in the file system with your static resources.
You need to configure access to your static resource by putting the following line in the {servlet-context.xml} file:



Serving resources from outside the context root
Now, this is accomplished by specifying an absolute path to the resource folder in the location attribute of the resources tag:



NOTE: don't forget to put the trailing slash at the end of the absolute path. It won't work if you miss that.
Serving resources from outside the context root - Windows path



Hope this will spare you some sleepless hours, because it took me a while to figure it out myself.

After context file configuration you should be able to serve images using a simple image tag.
viz.

Good Luck

1 comment: