13

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
shantan kumar
  • 147
  • 1
  • 1
  • 8

2 Answers2

9

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!

moffeltje
  • 4,521
  • 4
  • 33
  • 57
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
1

You can store/upload the files in the container. Use request.getRealPath("/") for accessing the path.

Example:

                byte[] bytes = fileInput.getBytes(); 

                //bytes to string conversion
                fileToStr = new String(bytes, "UTF-8");
                System.out.println(fileToStr);                    
                String name=fileInput.getOriginalFilename(); 

                String ext=name.substring(name.lastIndexOf("."),name.length()); 
                fileName=""+System.currentTimeMillis()+ext; 


                String rpath=request.getRealPath("/"); //path forstoring the file
                System.out.println(rpath); 
                File file=new File(rpath,"csv"); 
                if(!file.exists()){ 
                                file.mkdirs(); 
                } 

                File temp=new File(file,fileName); 
                System.out.println("Path : "+temp); 

                FileOutputStream fos= new FileOutputStream(temp); 
                fos.write(bytes); 
                fos.close(); 
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
  • Thank you karthik, I have tried the above code it is saving in the root directory of application can you please suggest me how to display that image is jsp, i am using spring mvc framework, I tried giving the full path of image but it failed,Please suggest me in this, Thanks in advance. – shantan kumar Feb 07 '15 at 12:14