我需要接收前端formdata数据,这个formdata里面可能有file文件也可能没有,请问怎么实现?

发布于 2022-09-12 22:55:28 字数 2218 浏览 21 评论 0

/**
 * 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情泪▽动烟 2022-09-19 22:55:28
public ResponseData insertCodeTaskForm(HttpServletRequest request, @RequestParam(required = false) MultipartFile file) {

@RequestParam(required = false) 可传可不传
@RequestParam(required = true) 必须传 默认是true 必须传

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文