0 本文主要涉及
在基于 Spring 和 SpringMVC 的前后端分离的 JavaWeb 项目中一种服务端识别上传文件 ContentType 方案的介绍说明
1 方案简介
在文件上传接口中识别出上传文件 ContentType ,通过配置实现限制上传文件类型以及不同文件上传大小限制功能
经过筛选实测最后选择的可用方案为通过 Apache Tika;其他方案出现识别错误,识别类型不全等问题。
2 配置实现
pom.xml 依赖配置
<!-- 识别 ContentType 只需引用core包即可-->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.26</version>
</dependency>
3 使用示例
public Result<Boolean> uploadToOSS(@Params OSSUploadParam ossUploadParam, MultipartFile file) throws IOException {
//基本入参判断代码省略
String contentType = tika.detect(file.getOriginalFilename());
log.info("contentType:{}", contentType);
if (StringUtils.isEmpty(Fi