前台jsp页:
Action中的关键代码:
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:附件信息已经成功保存到数据库");
}
这样就实现的动态的多文件上传.关键还是
的处理.
其中的数据库操作部分不是必须的.