如何在Vaadin中实现一键上传组件?

How to implement upload component with one upload button in Vaadin?

我有以下 class 实现单个上传示例

@Override
public void init() {
    Window mainWindow = new Window("Singleuploadclick Application");
    Label label = new Label("Hello Vaadin user");

    mainWindow.addComponent(label);

    status = new Label("Please select a file to upload");
    upload = new Upload(null, receiver);

    upload.setImmediate(true);
    upload.setButtonCaption("Select file");

    upload.addListener(new Upload.StartedListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void uploadStarted(StartedEvent event) {
            upload.setVisible(false);
            status.setValue("Uploading file \"" + event.getFilename() + "\"");
        }
    });

    upload.addListener(new Upload.ProgressListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void updateProgress(long readBytes, long contentLength) {
        }

    });

    upload.addListener(new Upload.SucceededListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void uploadSucceeded(SucceededEvent event) {
            status.setValue("Uploading file \"" + event.getFilename() + "\" succeeded");
        }
    });

    upload.addListener(new Upload.FailedListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void uploadFailed(FailedEvent event) {
            status.setValue("Uploading interrupted");
        }
    });

    upload.addListener(new Upload.FinishedListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void uploadFinished(FinishedEvent event) {
            upload.setVisible(true);
            upload.setCaption("Select another file");
        }
    });

    mainWindow.addComponent(status);
    mainWindow.addComponent(upload);            
    setMainWindow(mainWindow);
}

当运行应用程序时,上传组件的布局显示很奇怪。

所以我只需要一个上传按钮的上传组件,这就是我使用的原因:upload.setImmediate(true);

Button.setImmediate(true)用于选择文件后开始上传(无需点击按钮)。但是你仍然需要用 CSS.

隐藏按钮

引自Book of Vaadin 5.25 Upload

You can also hide the upload button with .v-upload .v-button {display: none} in theme, have custom logic for starting the upload, and call startUpload() to start it. If the upload component has setImmediate(true) enabled, uploading starts immediately after choosing the file.

因此您需要将此添加到您的自定义主题中:

.v-upload .v-button {
    display: none
}

以下css对我来说很好,谢谢你的好点

.gwt-FileUpload { 显示:none }