struts 1 中服务器端限制文件上传的类型及扩展名

src下建个properties文件,放置允许上传的文件类型:
allowuploadfiletype.properties
gif=image/gif
jpg=image/jpg,image/jpeg,image/pjpeg
bmp=image/bmp
png=image/png
swf=application/x-shockwave-flash
doc=application/msword
txt=text/plain
xls=application/vnd.ms-excel
ppt=application/vnd.ms-powerpoint
pdf=application/pdf
exe=application/octet-stream

 在BaseForm 里面写具体的验证方法:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class BaseForm extends ActionForm {

    private static Properties properties = new Properties();


    static{
        try {
            properties.load(BaseForm.class.getClassLoader().getResourceAsStream("allowuploadfiletype.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
    
   
    /**
    * 获取文件扩展名
    * @param formfile
    * @return
    */
    public static String getExt(FormFile formfile) {
        return formfile.getFileName().substring(
                formfile.getFileName().lastIndexOf('.') + 1).toLowerCase();
    }

    /**
    * 验证上传文件是否属于图片/flash动画/word文件/exe文件/pdf文件/TxT文件/xls文件/ppt文件
    * 
    * @param formfile
    * @return
    */
    public static boolean validateFileType(FormFile formfile) {
        if (formfile != null && formfile.getFileSize() > 0) {
            String ext = getExt(formfile);
            List<String> allowType = new ArrayList<String>();
            for (Object key : properties.keySet()) {
                String value = (String) properties.get(key);
                String[] values = value.split(",");
                for (String v : values) {
                    allowType.add(v.trim());
                }
            }
            return allowType.contains(formfile.getContentType().toLowerCase())
                    && properties.keySet().contains(ext);
        }
        return true;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值