---
title: "struts 1 中服务器端限制文件上传的类型及扩展名"
author: "siser344"
date: "2010-08-22T23:07:36Z"
tags: []
categories: ["企业架构"]
slug: "struts-1"
draft: false
lastmod: "2010-08-22T23:08:22Z"
id: 744612
url: "https://siser344.iteye.com/blog/744612"
---

```
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;
    }

}
```