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 !!!
getResourceAsStream(..)treats paths from the root of the classpath. And yours seems to be the root of the machine. So usenew FileInpuStream(fullPath)instead.In fact, there is another
getResourceAsStreammethod that belongs to theServletContext. It treats paths from the root of the web application, and is more suitable for web applications. (your web app root isDocuments-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>inweb.xmlfor example) that points to the absolute location of the uploads, and use theFileInputStreamapproach (orOutputStreamrespectively)