首页 > 解决方案 > 为什么 Upload.setAcceptMimeTypes 不能工作两次?

问题描述

提前抱歉,我的英语不太好。为什么,当我再次尝试上传文件时,我的 MIME 过滤器(由 setAcceptMimeTypes 安装)消失了,我可以再次看到所有文件?

第一次上传:

第二次上传:

我的代码:

@SpringUI
public class MyUI extends UI{
    @Value("${app.path}")
    private String basePath;
    @Value("${app.mimeTypes}")
    private String mimeType;
    @Value("${app.maxSize}")
    private int maxSize;
    private double fileSize;
    private File file;
    Upload upload;
    private OutputStream os = null;

@Override
protected void init(VaadinRequest request) {
    final VerticalLayout baseLayout = new VerticalLayout();
    TabSheet sample = new TabSheet();
    sample.setHeight(100.0f, Unit.PERCENTAGE);
    sample.addStyleName(ValoTheme.TABSHEET_FRAMED);
    sample.addStyleName(ValoTheme.TABSHEET_PADDED_TABBAR);

    HorizontalLayout uploadLayout = new HorizontalLayout();
    addUploadLayout(uploadLayout);
    HorizontalLayout downloadLayout = new HorizontalLayout();
    addDownloadLayout(downloadLayout);

    sample.addTab(uploadLayout, "Upload");
    sample.addTab(downloadLayout, "Download");

    baseLayout.addComponent(sample);
    setContent(baseLayout);
}

private void addUploadLayout(HorizontalLayout layout){
    upload = new Upload();
    upload.setImmediateMode(false);
    upload.setButtonCaption("Upload File");
    upload.setAcceptMimeTypes(mimeType);
    upload.setReceiver((Upload.Receiver) (filename, mimeType) -> {
        file = new File(basePath + filename);
        try {
            os = new FileOutputStream(file);
            return os;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    });

    upload.addProgressListener((readBytes, contentLength) -> {
        fileSize = (double) contentLength / 1024;
        if (fileSize > maxSize){
            upload.interruptUpload();
            Notification.show("Слишком большой файл.", Notification.Type.ERROR_MESSAGE);}
    });

    upload.addSucceededListener(event -> {
        DecimalFormat df = new DecimalFormat("0.00");
        Notification.show("Загрузка завершена, загружено " + df.format(fileSize) + " кб.", Notification.Type.TRAY_NOTIFICATION);
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    upload.addFailedListener(event -> {
        file.delete();
        Notification.show("Ошибка загрузки.", Notification.Type.TRAY_NOTIFICATION);
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    layout.setMargin(true);
    layout.addComponent(upload);
}

private void addDownloadLayout(HorizontalLayout layout){
    Label label = new Label("Hello People!!!");
    layout.setMargin(true);
    layout.addComponent(label);
}
}

标签: javavaadinvaadin8

解决方案


推荐阅读