Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where/How to store images/files in spring mvc [duplicate]

I am working in an e-commercial application in Spring MVC and Hibernate, where I need to store a number of images.
I want to save the images on a file system (on the server itself to reduce load on the database). My doubt is where exactly I should save images in my project?

As I have been through some blogs where it was mentioned that images should not be saved in folder with in war file as it can lead to problems when the next version of the app is released (to backup all images and again place them manually)
Please let me know where exactly I need to save images and how to get that folder path in our java class.

like image 771
shantan kumar Avatar asked Feb 07 '15 10:02

shantan kumar


1 Answers

You can create a controller that will return the image data and use it to display on your jsp.

Example controller:

@RequestMapping(value = "/getImage/{imageId}")
@ResponseBody
public byte[] getImage(@PathVariable long imageId, HttpServletRequest request)  {
    String rpath = request.getRealPath("/");
    rpath = rpath + "/" + imageId; // whatever path you used for storing the file
    Path path = Paths.get(rpath);
    byte[] data = Files.readAllBytes(path); 
    return data;
}

And use the below code for displaying:

<img src="/yourAppName/getImage/560705990000.png" alt="myImage"/>

HTH!

like image 184
karthik manchala Avatar answered Nov 16 '22 03:11

karthik manchala