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!
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
}
}