首先需要两个jar文件
commons-io-2.5.jar
commons-fileupload-1.3.1.jar
当然版本根据自己需要选择
设置文件上传配置,在spring配置文件,加入文件上传配置,如果不是不考虑
<!--文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<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">
</head>
<body>
<input type="file" id="fileSelect" name="file"/>
<input type="button" value="上传1" class="upload-file"/>
</body>
<script src="${pageContext.request.contextPath}/pages/js/jquery-2.1.1.js"></script>
<script src="${pageContext.request.contextPath}/pages/weixinpage/js/fileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
$(".upload-file").click(function(){
upload();
});
function upload(){
$.ajaxFileUpload({
url:"/fileController/upload.action",
type:"post",
secureuri:false,
fileElementId:"fileSelect",
dataType:"json",
success:function(res){
alert(res.mess+"上传成功");
},
error:function(){
alert("失败");
}
});
}
</script>
</html>
后台spring
package com.neutron.admin.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.http.HttpField;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.neutron.admin.model.dto.Json;
/**文件上传处理**/
@Controller
@RequestMapping("/fileController")
public class FileController {
@RequestMapping("/upload")
@ResponseBody
public Json upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) throws IllegalStateException, IOException{
Json json=new Json();
String path= request.getSession().getServletContext().getRealPath("/upload");
String fileName=file.getOriginalFilename();
File tfile=new File(path,fileName);//文件上传实质是javaio流,文件的复制,文件夹的创建
if(!tfile.exists()){//文件路径中的文件夹不存在,创建文件夹
tfile.mkdirs();
}
file.transferTo(tfile);
json.setMsg(request.getContextPath()+"/upload/"+fileName);
return json;
}
}