有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何保存上传的文件

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


共 (1) 个答案

  1. # 1 楼答案

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