环境:JDK6以上,这里我是用JDK8,mysql57,maven项目
框架环境:spring+springmvc+mybaits或spring+springmvc+mybatis plus
前端代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ajax文件上传</title> <script src="../js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> function savePic(){ alert("进来了"); var formData = new FormData($( "#uploadPic" )[0]); var ajaxUrl = "/LMS/user/saveHeaderPic"; //alert(ajaxUrl); //$('#uploadPic').serialize() 无法序列化二进制文件,这里采用formData上传 //需要浏览器支持:Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。 $.ajax({ type: "POST", url: ajaxUrl, data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) { alert("成功"); alert(data); }, error: function(data) { alert("error:"+data.responseText); } }); return false; } </script> </head> <body> <form id="uploadPic" action="#" enctype="multipart/form-data"> <input type="file" name="file"> <a href="#" class="btn green" onclick="savePic();"> 提交 </a> </form> </body> </html>
后台Controller
/** * 系统用户基本信息表 */ @RestController @RequestMapping("/user") public class UserController { /** * 头像图片上传 * @throws IOException */ @RequestMapping(value = "/saveHeaderPic", method = RequestMethod.POST) public void saveHeaderPic(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { String resMsg = ""; try { long startTime=System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); String path="E:\Demo\workspace\images\"+new Date().getTime()+file.getOriginalFilename(); System.out.println("path:" + path); File newFile=new File(path); //通过CommonsMultipartFile的方法直接写文件 file.transferTo(newFile); long endTime=System.currentTimeMillis(); System.out.println("运行时间:"+String.valueOf(endTime-startTime)+"ms"); resMsg = "1"; } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); resMsg = "0"; } response.getWriter().write(resMsg); } }