Search code examples
file-uploadprimefacestype-conversionapache-commons-vfs

Convert UploadedFile (primefaces) to FileObject (Apache Common)


I'm uploading a file using primefaces components.

   public void handleFileUpload(FileUploadEvent event) {
      UploadedFile file = event.getFile();
   }

For the further progress of the application, I have a function given from a library that I have to use. This function is only accepting a FileObject as input parameter.

How can I convert the UploadedFile (primefaces) to a FileObject (Apache Common)?

A workaround would be converting the UploadedFile to a File and then convert the file to a FileObject using VFS.getManager() and its functions. But to do this, I would have to save the file on the server and delete it later again.

I'm looking for a way, where I can convert the UploadedFile directly to a FileObject. Maybe by converting it to a bytearray first?

Glad for all suggestions.


Solution

  • Apache Commons VFS supports many different 'virtual file systems', one of them being 'RAM' which does not require storing in a real disk based file(system)

    You can use it something like this (disclaimer: not tested)

    public void handleFileUpload(FileUploadEvent event) {
    
        UploadedFile file = event.getFile();
    
        FileObject ram = VFS.getManager().resolveFile("ram:"+file.getFileName());
        OutputStream os = ram.getContent().getOutputStream();
        os.write(file.getContents());
        ram.getContent().close();
    
        // Use the ram FileObject
    }