【问题标题】:Vaadin Upload component how get fileName before submitUpload?Vaadin Upload 组件如何在 submitUpload 之前获取文件名?
【发布时间】:2014-03-26 15:14:25
【问题描述】:

我尝试在上传文件之前进行比较。

如果系统中存在同名文件,请询问是否创建新版本或直接覆盖它。

问题来了,如何获取文件名?

我不能使用receiveUpload(),因为在这个方法文件从上传组件中删除之后?

【问题讨论】:

标签: java file-upload vaadin


【解决方案1】:

问题是,一旦使用 Upload 组件开始上传,只能通过调用 interruptUpload() 方法中断上传,以后无法恢复。 中断是永久性的。

这意味着您不能在上传过程中暂停以查看系统中是否已有文件。您必须一直上传文件。

考虑到这个缺点,如果您有文件,您可以在上传完成后检查您的系统。如果您有该文件,您可以显示一个确认对话框,您可以在其中决定是保留该文件还是覆盖该文件。

如果文件已经上传,以下是我在“系统”中签入的示例(我只保留一个带有文件名的字符串列表):

public class RestrictingUpload extends Upload implements Upload.SucceededListener, Upload.Receiver {

private List<String> uploadedFilenames;
private ByteArrayOutputStream latestUploadedOutputStream;

public RestrictingUpload() {
    setCaption("Upload");
    setButtonCaption("Upload file");
    addSucceededListener(this);
    setReceiver(this);
    uploadedFilenames = new ArrayList<String>();
}

@Override
public OutputStream receiveUpload(String filename, String mimeType) {
    latestUploadedOutputStream = new ByteArrayOutputStream();
    return latestUploadedOutputStream;
}

@Override
public void uploadSucceeded(SucceededEvent event) {
    if (fileExistsInSystem(event.getFilename())) {
        confirmOverwrite(event.getFilename());
    } else {
        uploadedFilenames.add(event.getFilename());
    }
}

private void confirmOverwrite(final String filename) {
    ConfirmDialog confirmDialog = new ConfirmDialog();
    String message = String.format("The file %s already exists in the system. Overwrite?", filename);
    confirmDialog.show(getUI(), "Overwrite?", message, "Overwrite", "Cancel", new ConfirmDialog.Listener() {
        @Override
        public void onClose(ConfirmDialog dialog) {
            if (dialog.isConfirmed()) {
                copyFileToSystem(filename);
            }
        }
    });
}

private void copyFileToSystem(String filename) {
    try {
        IOUtils.write(latestUploadedOutputStream.toByteArray(), new FileOutputStream(filename));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

private boolean fileExistsInSystem(String filename) {
    return uploadedFilenames.contains(filename);
}

}

请注意,我使用了 2 个外部库:

您可以从 Gist 获取此类的代码 sn-p:https://gist.github.com/gabrielruiu/9960772,您可以将其粘贴到您的 UI 中并进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多