展示部分
1 <form style="display:none;" id="form-upload" method="post" enctype="multipart/form-data" action="/test/upload"> 2 <input type="hidden" name="id" value="123"> 3 <input type="file" name="file"> 4 </form> 5 <button class="btn-upload" id="btn-upload" >上传</button>
js事件绑定
1 <script type="text/javascript"> 2 (function(){ 3 // 劫持上传按钮点击事件,以做到文件上传自定义的目的 4 var objBtnFileUpload = $("#form-upload").find("input[type=‘file‘]"); 5 $("btn-upload").click(function(){ 6 objBtnFileUpload.trigger("click"); 7 }); 8 // 文件上传完成,input[type=‘file‘]改变,触发上传 9 objBtnFileUpload.change(function() { 10 var self = $(this); 11 var form = self.parent("form"); 12 var formData = new FormData(form[0]);//用这种方式获取值可以不触发页面跳转 13 $.ajax({ 14 type : form.attr(‘method‘), 15 url : form.attr(‘action‘), 16 data : formData, 17 mimeType : form.attr(‘enctype‘), 18 contentType : false, 19 cache : false, 20 processData : false 21 }).success(function(ret) { 22 console.log(ret); 23 alert("上传成功"); 24 }).fail(function(jqXHR, textStatus, errorThrown) { 25 //错误信息 26 console.log(jqXHR); 27 alert("上传失败!"); 28 }); 29 }); 30 } 31 })(); 32 </script>
后台处理
/** * <p>上传后台</p> * */ @RequestMapping(value = "/test/upload", method = RequestMethod.POST) @ResponseBody public String addFillForm(@RequestParam("file") MultipartFile file,HttpServletRequest request) { String id = request.getParameter("id");//额外的表单参数可以通过这种方式接收 byte[] bFile = file.getBytes(); String strFileName = file.getName(); //业务逻辑 return "上传成功"; }