struts.xml配置
<action name="saveUpload" class="com.hdz.base.action.UploadAction" method="save">
<param name="allowTypes">
image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,text/plain
</param>
<param name="savePath">d:\\upload</param>
</action>
action配置
private File upload;
private String uploadFileName;
private String uploadContentType;
private String allowTypes;
private String savePath;
public String save() {
String filterResult = filterType(this.getAllowTypes().split(","));
if (filterResult != null) {
setErrorInfo("您要上传的文件类型不正确");
return filterResult;
}
try{
File file = new File(getSavePath());
if(!file.exists()){
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+ getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
saveSession();
}catch(Exception e){
log.error(e.toString());
}
return SUCCESS;
}
public String filterType(String[] types) {
String fileType = this.getUploadContentType();
for (String type : types) {
if (type.equals(fileType)) {
return null;
}
}
return INPUT;
}
jsp页面
<s:form action="saveUpload" enctype="multipart/form-data" method="post">标题:<s:textfield name="title"></s:textfield>
名称:<s:file name="upload"></s:file>
<s:submit value="提交"></s:submit>
<s:property value="errorInfo"/>
</s:form>