MultipartFile+ajax图片上传

匿名 (未验证) 提交于 2019-12-03 00:30:01

今天调接口,一直报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;     }



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!