SpringBoot如何将Multipart和JSON上载到DTO上呢?
下文笔者讲述SpringBoot程序中将获取上传文件信息的方法分享,如下所示
实现思路: 1.定义接收Multipart对象的实体 2.定义表单 3.设置相应的Controller接收对象信息例:
//定义包装类 public class DataWrapper { private MultipartFile file; private String title; private String note; } //前端html页面 <form method="POST" enctype="multipart/form-data" id="fileUploadForm" action="link"> <input type="text" name="title"/><br/> <input type="text" name="note"/><br/><br/> <input type="file" name="file"/><br/><br/> <input type="submit" value="Submit" id="btnSubmit"/> </form> //定义接收表单的text数据和multipart文件 @PostMapping("/api/upload/multi/model") public ResponseEntity<?> multiUploadFileModel(@ModelAttribute FormWrapper model) { try { // Save as you want as per requiremens saveUploadedFile(model.getImage()); formRepo.save(mode.getTitle(), model.getDescription()); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded!", HttpStatus.OK); } //定义保存方法file private void saveUploadedFile(MultipartFile file) throws IOException { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。