views:

40

answers:

1

I am writing an upload and a download function, and I try to have this two methods to write to or read from the same folder, and I ran into some problem with getResourceAsStream. (The software is run on glassfish)

upload: The method upload to this folder: /home/phamtn8/glassfishv3/glassfish/domains/domain1/applications/Documents/Documents-war_war/drawings/Liandro.jpg --> work great

download: stream = the above path

input = this.getClass().getResourceAsStream(stream); //This return null

The location of the class files that contain these upload and download methods is at: /home/phamtn8/glassfishv3/glassfish/domains/domain1/applications/Documents/Documents-war_war/WEB-INF/classes/org/xdrawing/web. If I put the jpg file here, the getResourceAsStream work.

NOTE: this.getClass.getName() return org.xdrawing.web.FileName

Please help !!!

+7  A: 

getResourceAsStream(..) treats paths from the root of the classpath. And yours seems to be the root of the machine. So use new FileInpuStream(fullPath) instead.

In fact, there is another getResourceAsStream method that belongs to the ServletContext. It treats paths from the root of the web application, and is more suitable for web applications. (your web app root is Documents-war_war/)

But the best practice with file uploads and downloads is to store them in a totally different location from your web application - say /home/appname/uploads, so that you can deploy and undeploy the web-app without losing any data. You will just need a configuration option (a <context-param> in web.xml for example) that points to the absolute location of the uploads, and use the FileInputStream approach (or OutputStream respectively)

Bozho
awesome. thank you +1
Harry Pham