1. 先在页面处配置上传按钮:
form中需要添加 enctype="multipart/form-data" 参数,如下
<html:form action="/menuSmart.shtml" enctype="multipart/form-data" method="post">
以下为上传按钮,并外加显示连接
<td class="dvtCellLabel">菜单图片</td>
<td class="dvtCellInfo">
<html:file property="iconFile" />
<html:hidden property="icon"/>
<logic:notEmpty name="menuSmartForm" property="icon">
<a href="${menuSmartForm.icon}" target="_blank">查看</a>
</logic:notEmpty>
</td>
2. 以下为ACTION中的上传文件操作代码:
/**
* 文件上传
* @param form
* @param request
* @param isUpdate
* @return
* @throws Exception
*/
protected String simpleUpload(ActionForm form, HttpServletRequest request, boolean isUpdate) throws Exception {
MenuForm menuForm = (MenuForm) form;
String result="" ;
FormFile file = null;
FormFile[] files = new FormFile[]{menuForm.getIconFile(),menuForm.getBgImgFile()};
for (int i = 0; i < files.length; i++) {
file = files[i];
if (file != null && !file.getFileName().equals("")) {
String endName = FileUtil.getFileExt(file.getFileName());
if(!(endName.toUpperCase().equals("PNG")||endName.toUpperCase().equals("JPG")||endName.toUpperCase().equals("GIF"))){
log.info("上传的图标文件不是图片格式");
return null;
}
/*上至上传相对路径*/
String uploadPath = ("upload" + File.separator );
/*设置本地绝对路径*/
String uploadDir = servlet.getServletContext().getRealPath(uploadPath);
try {
/*创建文件流信息*/
File nwFile = new File(uploadDir);
/*判断是否存在改目录文件夹*/
if (!nwFile.exists())
nwFile.mkdirs();
long uid = System.currentTimeMillis();
/*获取文件后缀名*/
String fileExt = "." + endName;
String fname = uploadDir + File.separator + uid + fileExt;
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(fname);
int bytesRead = 0;
byte[] buffer = new byte[8192];
/*开始写文件*/
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
file.destroy();
String realName = "upload" + "/"+ uid + fileExt;
/*将真实的文件名设置到FORM中*/
if(i==0){
menuForm.setIcon(realName);
}
if(i==1){
menuForm.setBgImg(realName);
}
result = "upload" + File.separator + uid + fileExt;
} catch (Exception e) {
log.error("上传图片信息是发生异常:"+e);
return null;
}
}
}
return result;
}
3. 如果还需要对文档进行解压缩操作,以及其他的操作,请参考 本博客中标题为 “AJAX上传下载文件”的文章。