java - 如何保存上传的文件

标签 java vaadin eclipse-mars vaadin8

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

最佳答案

要在Vaadin中接收文件上传,您必须实现Receiver接口(interface),该接口(interface)为您提供一个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
    }
}

关于java - 如何保存上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215094/

相关文章:

java - 如何在 Vaadin 网格中仅使某些列可编辑?

java - 项目在转换为 Maven 后从所有接口(interface)方法被覆盖的地方抛出错误

java - 按父对象设置的子对象的值对父对象进行排序

java - 数组列表更新到数据库

vaadin - 在 Vaadin 7.4 应用程序中使用一组新数据更新网格

java - 如何在 Vaadin 中将 Keylistener 添加到 ListSelect?

java - 将 eclipse (不是工作区)移动到不同的目录

火星 eclipse : How to Stop Updating Error Reporting Database

java - 使用 tomcat 7 运行 Web 服务时出现 ClassNotFoundException?

java - 为什么 void 方法中不允许使用 this() ?