以下是一段用 Java 实现通过 `MultipartFile` 的 `contentType` 获取上传文件类型的代码示例: ```java import org.springframework.web.multipart.MultipartFile; public class FileTypeChecker { // 根据 MultipartFile 获取文件类型 public String getFileType(MultipartFile file) { String contentType = file.getContentType(); // 根据 contentType 判断文件类型 if (contentType.equalsIgnoreCase("image/jpeg")) { return "JPEG 图片"; } else if (contentType.equalsIgnoreCase("image/png")) { return "PNG 图片"; } else if (contentType.equalsIgnoreCase("application/pdf")) { return "PDF 文件"; } else { return "未知类型"; } } } ``` 额外需要注意的逻辑点: 1. 要处理可能获取到的 `contentType` 为空的情况。 2. 对于新出现的文件类型,需要及时更新判断逻辑。 3. 注意不同操作系统或环境下 `contentType` 的可能差异。 [2024-11-22 14:14:41 | AI写代码神器 | 242点数解答]