今天调接口,一直报org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file_data' is not present
,用postman能正常请求。觉得是前端写法有问题,网上查了下发现是js写法有问题,记录一下以后方便找
前端页面
<div id="uploadForm"> <input id="file" type="file"/> <button id="upload" type="button">upload</button> </div>js
$("#upload").on("click", function () {debugger; var s = $('#file')[0].files[0]; var formData = new FormData(); formData.append("file_data", s); formData.append("type", "1"); $.ajax({ url: "/jinhua-web/web/fileOption/fileUpload", type: 'POST', cache: false, data: formData, processData: false, contentType: false, success: function (result) { }, error: function (err) { } }); });
后端controller
@RequestMapping(value = "/fileUpload",method = RequestMethod.POST) public JSONObject fileUpload(@RequestParam("file_data") MultipartFile file_data, @RequestParam("type") String type, HttpServletRequest request){ JSONObject result = new JSONObject(); Path tempPath =Paths.get(Commonconstants.FILE_TEMP_PATH); tempPath = tempPath.resolve(type); Path realPath = Paths.get(rootPath,tempPath.toString()); if (!Files.exists(realPath)){ try { Files.createDirectories(realPath); } catch (IOException e) { result.put(Commonconstants.CODE,1); result.put(Commonconstants.MESSAGE,e.getLocalizedMessage()); e.printStackTrace(); return result; } } String fileName = UUID.randomUUID().toString().replace("-","")+".jpg"; tempPath = tempPath.resolve(fileName); realPath = realPath.resolve(fileName); try { file_data.transferTo(realPath.toFile()); } catch (IOException e) { result.put(Commonconstants.CODE,1); result.put(Commonconstants.MESSAGE,e.getLocalizedMessage()); e.printStackTrace(); return result; } result.put(Commonconstants.CODE,0); result.put("url",tempPath.toString()); return result; }
文章来源: MultipartFile+ajax图片上传