0

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.

cloudy_rowdy
  • 77
  • 1
  • 13
  • 3
    UploadFIle has both a getInputStream() and getContents() methods which return either the byte array or the stream. However to turn it into File you would have to use FileInputStream or some other means but all of those mean writing it to disk first. I am not sure there is an easy way of creating a File object without actually having an operating system file backing it. – Melloware Mar 23 '19 at 16:48
  • 1
    @Melloware: You can create a File object without having a real file on the operating system, it just won't have any data in it ;-). – Kukeltje Mar 26 '19 at 09:29
  • 1
    The FileObject as far as I see, always needs backing of something that is supported by the 'VFS'. If you check https://commons.apache.org/proper/commons-vfs/filesystems.html you can see which ones are supported. A 'RAM' one is available – Kukeltje Mar 26 '19 at 09:32

2 Answers2

1

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
}
Kukeltje
  • 12,223
  • 4
  • 24
  • 47
0

Maybe the easiest solution would be to simply build a custom implementation of FileObject that receives a FileUpload as a constructor parameter, extracts it's InputStream's contents and returns them as requested.

Look at the documentation to know the required methods.

Oscar Pérez
  • 4,377
  • 1
  • 17
  • 36