1.网页部分
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
/**部分代码省略**/
<form action="upload.html" method="post" enctype="multipart/form-data">
<input type="file" name="pic" /><input type="submit" value="提交" />
<!-- 显示上传图片的信息 -->
<c:if test="${empty error }"><input type="text" value="${pic }" class="package_path" />
</c:if>
</form>
2.控制器中(standardController.java)
@Controller
public class standardController {
private final int FILE_MAXSIZE = 500000;// 单个文件的最大的内存500KB
/* 上传文件 */
@RequestMapping(value = "/upload.html", method = RequestMethod.POST)
public String upload(HttpServletRequest request, Model model,
@RequestParam(required = false) MultipartFile pic) {
if(!pic.isEmpty()){
//1.获得文件的保存路径
String path=request.getServletContext().getRealPath("static"+
File.separator+"upload");
// 2.重命名文件(尽量保证每个上传的文件名都不重复,以免发生覆盖,导致资料丢失)
String oldFileName=pic.getOriginalFilename();//获得旧文件名
//获得旧文件名的后缀
String oldSuffix=FilenameUtils.getExtension(oldFileName);
// 2.1上传单个文件的大小
if(pic.getSize()>FILE_MAXSIZE ){//上传文件大小超出允许的最大内存
//保存错误信息
model.addAttribute("error", "单个文件大小不得超过500KB!");
//返回错误页面显示信息
return "uploadRet";
}else if(oldSuffix.equalsIgnoreCase("jpg")
|| oldSuffix.equalsIgnoreCase("png")
|| oldSuffix.equalsIgnoreCase("pneg")
|| oldSuffix.equalsIgnoreCase("jpeg")
|| oldSuffix.equalsIgnoreCase("gif")){// 判断文件格式是否符合条件
// 生成新的文件名 尽量保证不重复
String newFileName=System.currentTimeMillis()+"_"+
oldFileName.hashCode() + "." + oldSuffix;
//完成新文件的创建
File newPic=new File(path,newFileName);
// 2.2新建用于保存上传文件的文件夹
if (!newPic.exists()) {
newPic.mkdirs();// 如果文件夹不存在则自动创建文件夹
}
try {
// 3.将旧文件内容保存至新文件
pic.transferTo(newPic);// transferTo()方法是将文件储存到服务器上
model.addAttribute("info", "上传成功!");
model.addAttribute("pic", newFileName);// 文件上传成功后保存起来
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
model.addAttribute("error", "上传失败!");
}
} else {
model.addAttribute("error", "上传文件格式不正确!");
}
// 在这里可以调用biz保存信息或更新信息,其他表单值比如userName是可以直接使用
// 将新的文件名newFileName插入到数据库或更新到数据库
}
return "addNews";
}
3.错误信息显示页面
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
/**部分代码省略**/
<c:if test="${empty error }">
${info },上传的图片:<img src="statics/upload/${pic }" />
</c:if>
<c:if test="${not empty error }">
错误信息:${error }
</c:if>