限制文件类型上载组件

时间:2014-02-20 16:18:08

标签: java vaadin vaadin7

我正在使用vaadin的上传组件(7.1.9),现在我的麻烦是我无法限制哪些文件可以与上传组件一起发送到服务器,但我还没有'找到了用于此目的的任何API。唯一的方法是在上传后丢弃错误类型的文件。

public OutputStream receiveUpload(String filename, String mimeType) {

    if(!checkIfAValidType(filename)){
        upload.interruptUpload();
    }          

    return out;
}

这是正确的方法吗?

5 个答案:

答案 0 :(得分:7)

不,这不是正确的方法。事实上,Vaadin提供了许多有用的界面,您可以使用它们来监控上传开始,中断,完成或失败的时间。这是一个清单:

com.vaadin.ui.Upload.FailedListener;
com.vaadin.ui.Upload.FinishedListener;
com.vaadin.ui.Upload.ProgressListener;
com.vaadin.ui.Upload.Receiver;
com.vaadin.ui.Upload.StartedListener;

以下是一段代码示例:

@Override
public void uploadStarted(StartedEvent event) {
    // TODO Auto-generated method stub
    System.out.println("***Upload: uploadStarted()");

    String contentType = event.getMIMEType();
    boolean allowed = false;
    for(int i=0;i<allowedMimeTypes.size();i++){
        if(contentType.equalsIgnoreCase(allowedMimeTypes.get(i))){
            allowed = true;
            break;
        }
    }
    if(allowed){
        fileNameLabel.setValue(event.getFilename());
        progressBar.setValue(0f);
        progressBar.setVisible(true);
        cancelButton.setVisible(true);
        upload.setEnabled(false);
    }else{
        Notification.show("Error", "\nAllowed MIME: "+allowedMimeTypes, Type.ERROR_MESSAGE);
        upload.interruptUpload();
    }

}

此处, allowedMimeTypes 是一个mime类型字符串数组。

ArrayList<String> allowedMimeTypes = new ArrayList<String>();
allowedMimeTypes.add("image/jpeg");
allowedMimeTypes.add("image/png");

我希望它可以帮到你。

答案 1 :(得分:2)

可以做到。

你可以添加它,它可以工作(全部由HTML 5完成,大多数浏览器现在都支持accept属性) - 这是.csv文件的示例:

upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");

答案 2 :(得分:0)

我认为最好从Upload upload = new Upload(null, new Upload.Receiver() { @Override public OutputStream receiveUpload(String filename, String mimeType) { boolean typeSupported = /* do your check*/; if (!typeSupported) { throw new UnsupportedImageTypeException(); } // continue returning correct stream } }); public class UnsupportedImageTypeException extends RuntimeException { } 投出自定义异常:

upload.addFailedListener(new Upload.FailedListener() {
    @Override
    public void uploadFailed(Upload.FailedEvent event) {
        if (event.getReason() instanceof UnsupportedImageTypeException) {
            // do your stuff but probably don't log it as an error since it's not 'real' error
            // better would be to show sth like a notification to inform your user
        } else {
            LOGGER.error("Upload failed, source={}, component={}", event.getSource(), event.getComponent());
        }
    }
});

异常只是一个简单的自定义异常:

{{1}}

然后,如果上传失败,只需添加一个监听器,并检查原因是否是您的例外:

{{1}}

答案 3 :(得分:0)

公共静态布尔checkFileType(String mimeTypeToCheck){         ArrayList allowedMimeTypes = new ArrayList();

    allowedMimeTypes.add("image/jpeg");
    allowedMimeTypes.add("application/pdf");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    allowedMimeTypes.add("image/png");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.presentationml.presentation");
    allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    for (int i = 0; i < allowedMimeTypes.size(); i++) {
        String temp = allowedMimeTypes.get(i);
        if (temp.equalsIgnoreCase(mimeTypeToCheck)) {
            return true;
        }
    }

    return false;
}

答案 4 :(得分:0)

我正在使用Vaadin 8,并且上载类没有变化。

FileUploader receiver = new FileUploader();
Upload upload = new Upload();
upload.setAcceptMimeTypes("application/json");
upload.setButtonCaption("Open");
upload.setReceiver(receiver);
upload.addSucceededListener(receiver);

FileUploader是我创建的用于处理上传过程的类。让我知道是否需要查看实现。