在Spring Boot中接收JavaScript中的FormData传递的表单和文件,可以按照以下步骤进行: 1. 创建HTML表单并使用FormData对象收集数据: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload File</title> </head> <body> <form id="uploadForm" enctype="multipart/form-data"> <input type="text" name="name" placeholder="Name"> <input type="file" name="file" accept=".jpg, .jpeg, .png"> <button type="submit">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function () { $('#uploadForm').on('submit', function (event) { event.preventDefault(); const formData = new FormData(event.target); $.ajax({ url: '/api/upload', method: 'POST', data: formData, contentType: false, processData: false, success: function (response) { console.log(response); }, error: function (error) { console.error(error); } }); }); }); </script> </body> </html> ``` 2. 在Spring Boot应用中创建一个控制器来处理上传请求: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class UploadController { @PostMapping("/api/upload") public ResponseEntity<?> handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("Please select a file to upload"); } try { // 保存文件到服务器 byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); return ResponseEntity.ok(new MessageResponse("File uploaded successfully")); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new MessageResponse("Error occurred while uploading file")); } } private static final String UPLOADED_FOLDER = "src/main/resources/static/uploads/"; } ``` 3. 定义响应类MessageResponse: ```java public class MessageResponse { private String message; public MessageResponse(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ``` 4. 添加依赖项:确保你的pom.xml或build.gradle文件包含了Spring Web、Tomcat和Jackson相关的依赖项。 5. 运行Spring Boot应用并访问你的HTML页面,然后尝试提交表单。如果一切正常,你将看到控制台打印出文件上传成功的消息,并且文件会被保存到指定的目录下。 [2023-12-14 15:49:05 | AI写代码神器 | 644点数解答]