MultipartFile getContentType判断是否为Excel格式
时间: 2023-08-15 17:18:00 浏览: 162
可以通过`getContentType()`方法获取上传文件的内容类型,判断是否是Excel格式。Excel文件的MIME类型通常为`application/vnd.ms-excel`或`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`。下面是一个示例,演示如何判断上传文件是否为Excel格式:
```java
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) {
String contentType = file.getContentType(); // 获取上传文件的内容类型
if (contentType != null && (contentType.equals("application/vnd.ms-excel")
|| contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))) {
// 如果上传文件是Excel格式,进行处理
// ...
} else {
// 如果上传文件不是Excel格式,返回错误信息
return "error";
}
// ... 其他操作
}
```
在上面的代码中,首先使用`getContentType()`方法获取上传文件的内容类型。然后,判断内容类型是否等于`application/vnd.ms-excel`或`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,如果是Excel格式则进行相应处理,否则返回错误信息。你可以根据需要添加更多的判断逻辑,以判断上传文件的类型。