限制文件类型上载组件 [英] Restricting file types upload component

查看:168
本文介绍了限制文件类型上载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the upload component of vaadin(7.1.9), now my trouble is that I'm not able to restrict what kind of files that can be sent with the upload component to the server, but I haven't found any API for that purpose. The only way is that of discarding file of wrong types after the upload.

public OutputStream receiveUpload(String filename, String mimeType) {

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

    return out;
}

这是正确的方法吗?

推荐答案

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

No, its not the correct way. The fact is, Vaadin does provide many useful interfaces that you can use to monitor when the upload started, interrupted, finished or failed. Here is a list:

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类型字符串数组。

Here, allowedMimeTypes is an array of mime-type strings.

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

我希望它可以帮到你。

这篇关于限制文件类型上载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆