Struts1.2依然是应用很广的框架,实现动态多文件(不定个数)上传请先看下面的代码
关键代码
< SCRIPT language=javascript type=text/javascript > name="'+name+'" size=30 onchange="add();"/>'); < INPUT onclick=add(); value=多个附件 alt=手动添加文件域 type=button > |
Action中的关键代码:
FormFile[] formFile = null; |
upload方法:
/** *//**
* 文件上传的方法
*
* @param file
* @param request
* @param bbs
*/
public void upload(FormFile file, HttpServletRequest request, Bbs bbs)
{
//只有选择了文件时才上传
if ("".equals(file.getFileName()) || null == file.getFileName())
{
return ;
}
// 得到当前网站的绝对路径
String path = this.getServlet().getServletContext().getRealPath("/");
FileOutputStream fileOutput;
try
{
// 文件操作
fileOutput = new FileOutputStream(path + "main/upload/"
+ file.getFileName());
fileOutput.write(file.getFileData());
fileOutput.flush();
fileOutput.close();
log.info("BbsAction:附件上传成功");
}
catch (FileNotFoundException e)
{
log.info("BbsAction:找不到文件");
}
catch (IOException e)
{
log.info("BbsAction:文件IO异常");
}
// 数据库操作
Fileupload fileupload = new Fileupload();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + request.getContextPath()
+ "/";
fileupload.setFilename(basePath + "/main/upload/" + file.getFileName());
// 得到文件的扩展名
int point = file.getFileName().lastIndexOf(".");
String ext = file.getFileName().substring(point + 1);
//扩展名处理
if ("jpg".equals(ext.toLowerCase()) || "bmp".equals(ext.toLowerCase())
|| "gif".equals(ext.toLowerCase()))
{
ext = "img";
}
if ("rar".equals(ext.toLowerCase()) || "zip".equals(ext.toLowerCase())
|| "jar".equals(ext.toLowerCase()))
{
ext = "rar";
}
if("txt".equals(ext.toLowerCase()) || "sql".equals(ext.toLowerCase()) || "ini".equals(ext.toLowerCase()))
{
ext = "txt";
}
fileupload.setFileext(ext);
fileupload.setFilesize(file.getFileSize());
fileupload.setUptime(new Date());
fileupload.setDowncount(0);
fileupload.setUpuser(((User) request.getSession().getAttribute("user"))
.getUserName());
fileupload.setFlag((short) 0);
fileupload.setAnnounceId(bbs.getAnnounceId());
fileupload.setName(file.getFileName());
fileuploadManager.save(fileupload);
log.info("BbsAction:附件信息已经成功保存到数据库");
}
这样就实现的动态的多文件上传.关键还是
Hashtable files = bbsForm.getMultipartRequestHandler() |
您正在阅读的是“Struts1.2实现动态多文件(不定个数)上传”
【编辑推荐】