我在原有springmvc的web项目上新建jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传</title>
<Meta http-equiv="pragma" content="no-cache">
<Meta http-equiv="cache-control" content="no-cache">
<Meta http-equiv="expires" content="0">
<Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<Meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/ajaxfileupload.js"></script>
<script type="text/javascript"> function upload(){ $.ajaxFileUpload({ url:'uploadfile.do',secureuri:false,//是否启用安全提交,一般设置为false fileElementId:'uploadfile',//文件上传空间的id属性 <input type="file" id="uploadfile" name="uploadfile" /> dataType: 'json',//返回值类型 一般设置为json success:function(data,status){ //服务器成功响应处理函数 data = data.replace("<pre>","").replace("</pre>",""); data = eval('('+data+')'); if(data.flag=='success'){ //从服务器返回的json中取出message中的数据 alert("上传成功。"); $('#filepath').val(data.faceimagepath); $('#fileimage').attr("src","${pageContext.request.contextPath}/upload/userface/"+data.faceimagepath); }else if(data.flag=='typeerror'){ alert("图片类型错误,上传失败。"); }else{ alert("未知错误,上传失败!"); } },error: function (data,status,e){ //服务器响应失败处理函数 alert("服务器无法连接"); } }) } </script>
</head>
<body>
<input id="uploadfile" name="uploadfile" type="file">
<input type="button" value="上传" onclick="upload()">
<input id="filepath" name="filepath" type="text">
<div style="background:#fff;border:2px solid #99BBE8;padding: 0px;overflow:hidden;width: 220px;height: 220px;">
<img id="fileimage" alt="" src="">
</div>
</body>
</html>
引入jquery.1.8.3.js、ajaxfileupload.js文件。在这里路径要引用正确了,我在这却遇到了一个小问题,选择文件后点击上传页面却没有响应,根据以往的了解路径一定是没有错的,但在火狐浏览器firebug却报错提示$ is not defined.最后发现原来是项目中配置的过滤器的原因,于是我在web.xml文件中添加:
<!-- 过滤器配置 -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.springtest.common.filter.LoginFilter</filter-class>
<init-param>
<param-name>notFilterDir</param-name>
<param-value>
/login.do,/userlogin.do,/fileupload.jsp,/uploadfile.do,/js/
</param-value>
</init-param>
</filter>
<!-- Filter映射 -->
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
将js文件夹过滤出来,这样我在uploadfile.do就可以请求到了。
//上传文件
@RequestMapping(value = "/uploadfile.do",method = RequestMethod.POST)
public void uploadUserFace(PrintWriter out,HttpServletRequest request,HttpSession session) {
try {
String filefolderpath = session.getServletContext().getRealPath("");
filefolderpath += File.separator + "upload" + File.separator+ "userface" + File.separator;
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
List fileList = upload.parseRequest(request);
Iterator it = fileList.iterator();
String name = null;
String preName = null;
String extName = null;
String filename = null;
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()) {
name = item.getName();
long size = item.getSize();
String type = item.getContentType();
if (name == null || name.trim().equals("")) {
continue;
}
// 文件名:
if (name.lastIndexOf(".") >= 0) {
preName = name.substring(0,name.lastIndexOf("."));
}
// 扩展名格式:
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf(".")).toLowerCase();
}
if (extName.equals(".bmp") ||extName.equals(".gif") ||extName.equals(".jpg") || extName.equals(".jpeg")) {// 是Image
filename =DateUtil.formatDate(new Date(),"yyyyMMddHHmmssSSS");
File saveFile = new File(filefolderpath + filename+ extName);
item.write(saveFile);
out.print("{\"flag\":\"success\",\"faceimagepath\":\""+ filename + extName + "\"}");
} else {
out.print("{\"flag\":\"typeerror\"}");
}
}
}
} catch (Exception e) {
e.printStackTrace();
out.print("{\"flag\":\"error\"}");
} finally {
out.flush();
out.close();
}
}
如果项目中没有upload/userface文件夹:会提示系统找不到文件路径。
手动在项目中建两个upload/userface文件夹,图片上传成功。但是jsp页面$.ajaxFileUpload()success回调却没有响应。
在我这个环境中,out.print()返回的字符串在jsp页面却没有获取成功。firebug报错提示:
在ajaxfileupload.js文件中,我也不知道是怎么回事,这个问题先留在这。
我用的服务器是jboss7.x,这个版本的服务器有个特点,每次修改文件后ctrl+s好像都会重新部署,console会打印出:
23:40:36,514 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/springtest]] (MSC service thread 1-7) Destroying Spring FrameworkServlet 'DispatcherServlet'
23:40:36,666 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/springtest]] (MSC service thread 1-7) Closing Spring root WebApplicationContext
23:40:36,917 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) Stopped deployment springtest.war in 405ms
23:40:36,918 INFO [org.jboss.as.server.deployment] (MSC service thread 1-5) Starting deployment of "springtest.war"
相比起来我还是更喜欢jboss4.x。可能是7.x的版本需要在哪修改下配置,这个问题也先留着。