如何保存上传的文件

How to save uploaded file

我想知道如何从 Vaadin 上传组件获取文件。这是 Vaadin Website 上的示例 但除了关于 OutputStreams 的内容外,它不包括如何保存它。 求助!

要在 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
    }
}