How to write a file to resource/images folder of the app?

I would like to store it in “resources/images” of the app

No, please don’t. The WAR deploy space isn’t intented as permanent file storage location. All of those uploaded files would get lost whenever you redeploy the webapp for the very simple reason that they are not contained in the original WAR. See for an elaborate explanation also this answer on a very closely related question: Uploaded image only available after refreshing the page.


Right now, the file goes to “domain1\generated\jsp\FileUpload”.

Because you specified a relative path in Part#write(). It becomes relative to the current working directory which you have no control over. See for an elaborate explanation also this related answer: getResourceAsStream() vs FileInputStream. You need to specify an absolute path, in other words, start the path with /.


Given that you’re using Glassfish, the answer in Uploaded image only available after refreshing the page should also do it for you. In a nutshell:

  1. Create a /var/webapp/images folder. Note that this path is just examplary and fully free to your choice. Also note that when you’re using Windows with a C:\ disk, then this path is equivalent to C:\var\webapp\images.

  2. Save the uploaded file in there.

    Path file = Files.createTempFile(Paths.get("/var/webapp/images"), "somefilename-", ".jpg", );
    
    try (InputStream input = uploadedFile.getInputStream()) {
        Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
    }
    
    imageFileName = file.getFileName().toString();
    // ...
    

    (note: Files#createTempFile() is being used to autogenerate an unique filename, otherwise a previously uploaded file would get overwritten when the new uploaded file (by coincidence) has exactly the same filename)

  3. Tell GlassFish to register a virtual host on /var/webapp/images so that all files are available on http://example.com/images by adding the following entry to /WEB-INF/glassfish-web.xml of the webapp:

    <property name="alternatedocroot_1" value="from=/images/* dir=/var/webapp" />
    

    (note: alternatedocroot_1 must be exactly like that, keep it unmodified, if you have multiple, name it alternatedocroot_2, etc; also note that the /images part should indeed not be included in dir attribute, this is not a typo)

  4. Now you can display it as follows:

    <h:graphicImage value="/images/#{bean.imageFileName}" />
    

    (note: use value attribute, not name attribute)

Leave a Comment