我需要接收前端formdata数据,这个formdata里面可能有file文件也可能没有,请问怎么实现?
/**
* form * @param request
* @return
*/
@RequestMapping(value = "/v2/code-task", method = {RequestMethod.POST})
public ResponseData insertCodeTaskForm(HttpServletRequest request, @RequestPart(value = "file") MultipartFile file) {
String code = "500";
String status = "fail";
String message = "fail";
String detail = "";
JSONObject jsonTechnologyArticle = JSON.parseObject("{}");
String title = request.getParameter("title");
String content = request.getParameter("content");
CodeTask codeTask = new CodeTask();
logger.info("file == " + file);
try {
/*
* 这段代码执行完毕之后,图片上传到了工程的跟路径; */ BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(
file.getOriginalFilename())));
// logger.info(file.getOriginalFilename());
out.write(file.getBytes());
out.flush();
out.close();
logger.info("insertCodeTaskForm ==" + request.getParameter("title"));
codeTask.setTitle(title);
codeTask.setTitle(content);
codeTask.setTaskCover(file.getOriginalFilename());
codeTask.setUserID(2);
Integer idTask = codeTaskService.insertTask(codeTask);
code = "200";
status = "success";
message = "success";
jsonTechnologyArticle.put("taskId", codeTask.getId());
detail = "等待审核中";
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.info("上传失败," + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.info("上传失败," + e.getMessage());
}
ResponseData responseData = ResponseUtility.handleData(
code, status, message,
detail, jsonTechnologyArticle);
return responseData;
}
2021-03-22 17:19:41.570 [http-nio-9091-exec-1] INFO [173] - Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-03-22 17:19:41.570 [http-nio-9091-exec-1] INFO [521] - Initializing Servlet 'dispatcherServlet'
2021-03-22 17:19:41.583 [http-nio-9091-exec-1] INFO [543] - Completed initialization in 13 ms
2021-03-22 17:19:41.690 [http-nio-9091-exec-1] WARN [194] - Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@RequestParam(required = false) 可传可不传
@RequestParam(required = true) 必须传 默认是true 必须传