JQueryAjax使用SpringMVC中MultipartFile進行檔案上傳的整合
阿新 • • 發佈:2019-01-04
對於一個帶有檔案上傳的表單,後臺使用springMVC封裝的MultipartFile file接收檔案,並且需要使用非同步提交,並返回相應的提示資訊
在這種情況下,我最開始使用了好幾種方法
第一種:普通的JQUERY的AJAX,但是後臺一旦使用MultipartFile 這個類接收就會報request的一個異常BUG,這種方法不行
第二種:使用JQUERY的普通表單提交,也就是submit,後臺使用springMVC,這種情況可以實現,但是後臺必須跳轉頁面,也就是無法非同步提交
於是產生了第三種方法
第三種:使用JQUERY的form外掛,即jquery.form.js這個外掛,然後使用外掛的ajaxSubmit方法;程式碼如下
前端:
$("#pageForm").ajaxSubmit({
type: "POST",
url:"你的action.html",
dataType: "json",
success: function(data){
if(data.msg=='SUCCESS'){
alert(success);
}
else{
alert(data.msg);
}
}
});
後端:
這樣既能解決檔案傳值,又能非同步提交了@RequestMapping("/insertGoodsBrand") public void insertGoodsBrand( HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response, GoodsBrand goodsBrand){ JSONObject obj = new JSONObject(); PrintWriter out = null; try { out = response.getWriter(); String path = request.getSession().getServletContext().getRealPath( "upload\\goods\\brand"); String fileName = file.getOriginalFilename(); String saveFileName = Common.getNowCorrect2Second() + "." + fileName.substring(fileName.lastIndexOf(".") + 1); File targetFile = new File(path, saveFileName); if (!targetFile.exists()) { targetFile.mkdirs(); } String msg = ""; file.transferTo(targetFile); msg = backGoodsBrandBus.insertGoodsBrand(goodsBrand, saveFileName); if (msg.equals("SUCCESS")) { obj.put("msg", msg); } else { obj.put("msg", msg); } out.print(obj); } catch (Exception e) { e.printStackTrace(); } finally{ out.close(); } }