如何保存上传的文件

时间:2017-09-14 09:16:22

标签: java vaadin eclipse-mars vaadin8

我想知道如何从Vaadin上传组件中获取文件。以下是Vaadin Website的示例 但除了OutputStreams之外,它不包括如何保存它。 救命啊!

1 个答案:

答案 0 :(得分:2)

要在Vaadin中接收文件上传,您必须实现Receiver界面,它为您提供receiveUpload(filename, mimeType)方法,用于接收信息。执行此操作的最简单的代码是(以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
    }
};

有了这个,Uploader会在C:\中写一个文件。如果您希望在上传成功完成后获得某些内容,则可以实施SucceeddedListenerFailedListener。以上面的例子为例,结果(SucceededListener)可以是:

class FileUploader implements Receiver {
    //receiveUpload implementation

    public void uploadSucceeded(SucceededEvent event) {
        //Do some cool stuff here with the file
    }
}