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, e.g. /images
or so. In a Windows environment this will automatically refer to the disk from where the webapplication is started, e.g. 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.