0

Users can upload images on my website. My servlet needs to write the uploads into directory images of my webapp. For writing it onto the disk I need to create a File() object.

One way is that I can hardcode the complete path to something like

new File("/usr/tomcat/webapps/ROOT/images/file.jpg")

Is there a way so that I can specify something like new File("images/file.jpg").. Can I do it using new File (URI uri ) so that I do not have to hardcode the complete path. My servlet is located inside /usr/tomcat/webapps/ROOT/WEB-INF/classes/

The images folder is not a directory. It is actually a symbolic link which is pointing to another directory on the filesystem outside tomcat

Deepak Singhal
  • 10,568
  • 11
  • 59
  • 98

3 Answers3

2

Don't store images under your webapp deployment directory: next time you'll redeploy the app, you will lose all your images. And moreover, there is not always a directory for a webapp, since it's typically deployed as a war file.

Store your images in an external location, at an absolute path, and configure Tomcat or another web server to serve images from this location, or implement a servlet which serves images from this location.

See Image Upload and Display in JSP for additional pointers.

EDIT:

If your problem is the hard-coded absolute path in the Java code, use a System property that you set when starting Tomcat, or a context param in the web.xml, or use a properties file to store the path, or your database.

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

You can get the web app path from the ServletContext object. You get the ServletContext from the HttpServletRequest object (http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServletContext%28%29).
See http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29
Concatenate the "real path" to the desired image file path and provide this as the parameter to the File constructor.

Oded Peer
  • 2,377
  • 18
  • 25
0
 try{    

String directory = //Store it in your Property file and pick it 

String filename= //Generate Dynamic name or any specific format 
   // Create file    
  FileWriter fstream = new FileWriter(directory+filename);   
  BufferedWriter out = new BufferedWriter(fstream);  
    out.write("your content"); }
catch (Exception e){   
  System.err.println("Error: " + e.getMessage()); }
finally {  
   //Close the output stream
     out.close();
 } 

You Can keep the directory path in you property file if it is not changing frequently. Directory name can be absolute path which may be a hardrive path or you can save it in your webapp also but it always advisable any input file keep it outside the webapp.

File naming is always up to you if you want to keep the same file name then need to handle duplicate check other wise specify some dynamic format and named it.

BOSS
  • 2,931
  • 8
  • 28
  • 53