實例頁面如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script> </head> <body> <form id="form1" action="" method="post" enctype="multipart/form-data"> 選擇上傳文件:<input type="file" name="file" id="file"/><br> <input type="button" value="ajax提交" id="ajaxSub"> </form> <script type="text/javascript" > //此對象用來封裝其他參數 function ParamList(firstParam,secondParam,thirdParam) { this.firstParam = firstParam; this.secondParam = secondParam; this.thirdParam = thirdParam; }; //事件 $("#ajaxSub").click(function () { //存放對象參數的數組 var dataList = new Array(); var object = new ParamList("被申請人","男,","。"); dataList.push(object); var object1 = new ParamList("仲裁庭認爲",",","案涉商品簽約價3319"); dataList.push(object1); var object2 = new ParamList("商品名稱",":","元;"); dataList.push(object2); var object3 = new ParamList("若被申請人","若被申請人","違約金額。"); dataList.push(object3); console.log(dataList); //創建一個FormData對象,用來封裝所需參數 var myform = new FormData(); //獲取form表單中的文件 myform.append('file', $('#file')[0].files[0]); //用戶id myform.append('userId','1'); //用戶名稱 myform.append('userName','張三'); //將對象數組轉化成json串傳遞給後臺 myform.append("paramList",JSON.stringify( dataList )); //var fromData = $("#form1").serialize(); //發送ajax請求 $.ajax({ url:"http://192.168.34.132:8083/api/verdict", type:"post", data:myform, contentType: false, processData: false, success:function (obj) { console.log(obj) } }); }); </script> </body> </html>
下列爲後臺controller接收前臺傳遞參數的部分代碼,只要是從MultipartHttpServletRequest獲取附件信息。
@RequestMapping(value = "/api/verdict") public JsonResult<String> grabWordFromVerdictPdf(@RequestParam(value = "userId", required = false) Integer userId, @RequestParam(value = "userName", required = false) String userName, @RequestParam(value = "paramList", required = false) String paramList, MultipartHttpServletRequest request) { Iterator<String> fileNames = request.getFileNames(); MultipartFile file = null; JsonResult<String> jsonResult = new JsonResult<String>(); while (fileNames.hasNext()) { String str = fileNames.next(); file = request.getFile(str); } if (file != null) { String fileName = file.getOriginalFilename(); String suffix = ""; if (fileName != null) { suffix = fileName.substring(fileName.indexOf("."), fileName.length()); } String localPath = uploadFileConfig.getLocalPath(); String interPath = uploadFileConfig.getInterPath(); }
}