酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

写一个springboot的上传接收excel的controller例子

在Spring Boot中,我们可以使用`MultipartFile`来处理文件上传,包括Excel文件。以下是一个简单的Controller示例,它接收一个Excel文件并将其保存到服务器: 首先,你需要在pom.xml文件中添加Apache POI依赖,用于解析Excel文件: ```xml <dependencies> ... <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ... </dependencies> ``` 然后创建一个Controller类,例如`FileUploadController`: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; public class FileUploadController { @Value("${file.upload.path}") private String uploadPath; @PostMapping("/upload-excel") public ResponseEntity<String> uploadExcel(@RequestParam("file") MultipartFile file) { if (file == null || file.isEmpty()) { return ResponseEntity.badRequest().body("File is empty"); } try { // 检查文件类型是否为Excel if (!file.getOriginalFilename().toLowerCase().endsWith(".xls") && !file.getOriginalFilename().toLowerCase().endsWith(".xlsx")) { return ResponseEntity.badRequest().body("Invalid file type, only Excel files (.xls, .xlsx) are allowed"); } // 创建目标文件路径 Path targetFile = Paths.get(uploadPath, file.getOriginalFilename()); // 将文件从内存复制到服务器 Files.copy(file.getInputStream(), targetFile, StandardCopyOption.REPLACE_EXISTING); return ResponseEntity.ok("File uploaded successfully: " + targetFile); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while uploading file: " + e.getMessage()); } } } ``` 在这个例子中,我们首先检查上传的文件是否为空或类型是否为Excel。然后,我们将文件从请求体复制到服务器上的指定目录(可以通过`@Value`注解配置)。 注意:这个例子没有包含Excel内容的解析,如果你需要解析Excel内容,你可能需要使用Apache POI或者其他的库,这将涉及到更复杂的代码和逻辑。 [2024-04-01 12:12:38 | AI写代码神器 | 525点数解答]

相关提问