0

I would like to know how to get a file from a Vaadin Upload Component. Here is the example on the Vaadin Website but it does not include how to save it other than something about OutputStreams. Help!

Auscyber
  • 72
  • 1
  • 2
  • 13
  • 1
    As said in docs, you have a method called `receiveUpload`. In this method, you take a filename and its mime type. Then you must create an `OutputStream`[(java 7 doc)](https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html) with a `File` with that filename and return it... Of course, the `File` must be located where you want to save the upload. – Shirkam Sep 14 '17 at 09:28
  • @Shirkam Can I have some code? as location being C:\ – Auscyber Sep 14 '17 at 09:34
  • 1
    Yeah why not, stackoverflow is your cost-free programmer community... – Steffen Harbich Sep 14 '17 at 11:10

1 Answers1

4

To receive a file upload in Vaadin, you must implement Receiver interface, wich provides you with a receiveUpload(filename, mimeType)method, used to receive the info. The simplest code to do this would be (Taken as example from Vaadin 7 docs):

class FileUploader implements Receiver {
    private File file;
    private String BASE_PATH="C:\\";

    public OutputStream receiveUpload(String filename,
                                  String mimeType) {
        // Create upload stream
        FileOutputStream fos = null; // Stream to write to
        try {
            // Open the file for writing.
            file = new File(BASE_PATH + filename);
            fos = new FileOutputStream(file);
        } catch (final java.io.FileNotFoundException e) {
            new Notification("Could not open file<br/>",
                         e.getMessage(),
                         Notification.Type.ERROR_MESSAGE)
            .show(Page.getCurrent());
            return null;
        }
        return fos; // Return the output stream to write to
    }
};

With that, the Uploader will write you a file in C:\. If you wish to something after the upload has completed successfully, or not, you can implement SucceeddedListener or FailedListener. Taking the example above, the result (with a SucceededListener) could be:

class FileUploader implements Receiver {
    //receiveUpload implementation

    public void uploadSucceeded(SucceededEvent event) {
        //Do some cool stuff here with the file
    }
}
Shirkam
  • 744
  • 6
  • 20