Skip to content
Advertisement

How to get the File from an Upload component in Vaadin

I’m new with Vaadin, and I don’t know how to get the File from the Upload component, I’m always having a server error. I don’t think I understand properly how this works. Any help will be welcome. This is my code.

public MainView() {
    HorizontalLayout horizontalLayout = new HorizontalLayout();
    horizontalLayout.add(
            new H1("Stop Motion Creator")
    );
    add(horizontalLayout);

    MemoryBuffer memoryBuffer = new MemoryBuffer();
    Upload midiFileUpload = new Upload(memoryBuffer);
    midiFileUpload.setMaxFiles(1);
    midiFileUpload.setDropLabel(new Label("Upload a file in .mid format"));
    midiFileUpload.setAcceptedFileTypes("mid");
    midiFileUpload.setMaxFileSize(10);

    midiFileUpload.addSucceededListener(event -> {
        InputStream inputFileData = memoryBuffer.getInputStream();
        String fileName = event.getFileName();
        long contentLength = event.getContentLength();
        String mimeType = event.getMIMEType();

        Receiver receiver = new Receiver() {
            @Override
            public OutputStream receiveUpload(String s, String s1) {
                return null;
            }
        };
        OutputStream outputFileData = receiver.receiveUpload(fileName, mimeType);
        FileData filedata = new FileData(fileName, mimeType,outputFileData);
        File midiFile = filedata.getFile();
}

Advertisement

Answer

Here’s a code sample from one of my projects

FileUploader buffer = new FileUploader();    
upload.setReceiver(buffer);
upload.setAcceptedFileTypes("image/jpeg", "image/png");
upload.addSucceededListener(event -> {
            try {
                File file = new File(buffer.getFilename());
                // Do whatever with file object
            } catch (IOException e) {
                e.printStackTrace();
            }
});

FlieUploader.java

public class FileUploader implements Receiver {
    public static String BASE_PATH = "/tmp/";
    private File file;
    private String filename;

    public OutputStream receiveUpload(String filename,
                                      String mimeType) {
        // Create upload stream
        FileOutputStream fos = null; // Stream to write to
        try {
            // Open the file for writing.
            this.filename = FileUploader.BASE_PATH + filename;

            file = new File(this.filename);
            fos = new FileOutputStream(file);
        } catch (final java.io.FileNotFoundException e) {
            return null;
        }
        return fos; // Return the output stream to write to
    }

    public String getFilename() {
        return filename;
    }
};
Advertisement