Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to upload an image and store it on the server, and later to show it with h:graphicImage? I would like to store it in "resources/images" of the app. I am using glassfish 4. Right now, the file goes to "domain1\generated\jsp\FileUpload". Thank you

My form

<h:form id="form" enctype="multipart/form-data">
        <h:messages/>
        <h:panelGrid columns="2">
            <h:outputText value="File:"/>
            <h:inputFile id="file" value="#{uploadPage.uploadedFile}"/>
        </h:panelGrid>
        <br/><br/>
        <h:commandButton value="Upload File" action="#{uploadPage.uploadFile}"/>
</h:form>

My bean

@Named
@ViewScoped
public class UploadPage {       
    private Part uploadedFile; 

    public void uploadFile(){
       File file = File.createTempFile("somefilename-", ".jpg", new File("C:\\var\\webapp\\images"));
    uploadedFile.write(file.getAbsolutePath());

    }
}
like image 946
Pavel Avatar asked Oct 02 '13 14:10

Pavel


People also ask

How do I add a resource folder to a jar file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR! EDIT: you can make sure your JAR contains folder by inspecting it using 7zip. Save this answer.

What is a resource folder?

A resource folder is a folder used in android devices that help to store data in one or more files or folder within the same folder name Resource. This is used with the help of API using a special android runtime app.

What is resource folder in Android?

The res/values folder is used to store the values for the resources that are used in many Android projects to include features of color, styles, dimensions etc.


2 Answers

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)

like image 69
BalusC Avatar answered Nov 16 '22 04:11

BalusC


Wasn't able to get it working with Path#write in glassfish, so I used Path#getInputStream as follows:

public void upload(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            String filename = getFilename(uploadedFile);
            File file = new File("/var/webapp/images/"+filename);
            bis = new BufferedInputStream(uploadedFile.getInputStream());
            FileOutputStream fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            int x;
            while((x = bis.read())!= -1){
                bos.write(x);
            }
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                bos.flush();
                bos.close();
                bis.close();
            } catch (IOException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
like image 44
Dapope Avatar answered Nov 16 '22 04:11

Dapope