您的位置:首页 > 编程语言 > Java开发

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

2008-10-11 13:39 519 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: