简体   繁体   中英

How can I get the package path of a JSF managed bean?

I'm trying to upload an external image and I need to save it in a folder where I have a managed bean. Any idea how I could do this?

Use Class#getResource() to obtain the URL where the class is located.

URL beanClassPath = Bean.class.getResource("");
File imageFile = new File(beanClassPath.getPath(), imageFileName);
// ...

However, this is generally a very bad idea. If you redeploy the webapp, everything will get lost. Rather store the images in a fixed path somewhere outside the webapplication, eg /images or so. In a Windows environment this will automatically refer to the disk from where the webapplication is started, eg c:/images .

File imageFile = new File("/images", imageFileName);
// ...

You can also consider to store them in a database, you'll only need to store some metadata along it, such as the original filename, content type and preferably also the content length and eventually the creation and last modification timestamps. That kind of information which you would usually obtain using the java.io.File methods. You'll namely going to need them whenever you'd like to serve the image back to the webpage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM