1、首先在pom.xml文件中添加依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2、在applicationContext.xml配置文件添加配置
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="-1"/>
</bean>
3、HTML代码
<div>
<form action="#" id = "uploadForm" method="post" enctype="multipart/form-data">
<div>
<label>姓名:</label>
<input id="name" name="name">
</div>
<div>
<label>密码:</label>
<input id="password" name="password" type="password">
</div>
<div>
<label>图像</label>
<input id="file" name="file" type="file" multiple>
</div>
</form>
<button id="submit">提交</button>
</div>
4、JavaScript代码
<script type="text/javascript">
$("#submit").click(function(){
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url : 'file/upload',
data:formData,
type:'post',
dataType:'json',
success:function(data){}
});
});
</script>
5、服务端接收代码:
/**
* 文件上传
* @param file
* @param request
* @throws IOException
*/
@RequestMapping("/upload")
@ResponseBody
public void upload(MultipartFile file,HttpServletRequest request)
throws IOException{
if(file.isEmpty()){
logger.info("文件不存在!");
}else{
logger.info("文件存在!");
String fileName = file.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("/")+"/upload";
File dirFile = new File(path,fileName);
if(!dirFile.getParentFile().exists()){
dirFile.getParentFile().mkdirs();
}
String filePath = path + File.separator +fileName;
file.transferTo(new File(filePath));
}
}
运行jsp就可以了,但是图片在eclipse中是看不到的,只要打包成war包,到Tomcat中可以看到。