MultipartFile 判断文件类型
时间: 2023-08-25 07:13:22 浏览: 416
您可以使用Java的MultipartFile类来判断文件类型。以下是一个示例代码:
```java
import org.springframework.web.multipart.MultipartFile;
public class FileTypeChecker {
public static String getFileContentType(MultipartFile file) {
String contentType = null;
try {
contentType = file.getContentType();
} catch (Exception e) {
e.printStackTrace();
}
return contentType;
}
public static void main(String[] args) {
MultipartFile file = ... // 从请求中获取上传的文件
String contentType = getFileContentType(file);
if (contentType != null) {
System.out.println("文件类型:" + contentType);
} else {
System.out.println("无法确定文件类型");
}
}
}
```
在上面的示例中,`getFileContentType`方法使用`getContentType`方法从MultipartFile对象中获取文件的内容类型。如果无法确定文件的类型,将返回null。
请注意,这只能检查文件的内容类型,而不是文件的扩展名。如果您需要检查文件的扩展名,可以使用`getOriginalFilename`方法获取文件名,并根据扩展名进行判断。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)