在 java 的 web 后端(如 spring boot)中,限制文件上传类型通常通过判断 multipartfile
的 content-type(mime 类型)或文件扩展名(后缀名)来实现。
一、限制文件类型的常见做法
方法 1:根据multipartfile.getcontenttype()判断 mime 类型
public void validatefiletype(multipartfile file) { list<string> allowedtypes = list.of("image/png", "image/jpeg", "application/pdf"); string contenttype = file.getcontenttype(); if (!allowedtypes.contains(contenttype)) { throw new illegalargumentexception("不支持的文件类型: " + contenttype); } }
注意:浏览器伪造 content-type 是可能的,因此推荐再结合后缀判断或做文件头检查(magic number)
方法 2:根据文件名后缀判断类型(不安全但能挡住大部分无意误传)
public void validateextension(multipartfile file) { string filename = file.getoriginalfilename().tolowercase(); list<string> allowedextensions = list.of(".jpg", ".jpeg", ".png", ".pdf"); if (allowedextensions.stream().nonematch(filename::endswith)) { throw new illegalargumentexception("不支持的文件后缀"); } }
方法 3:安全性更高 —— 检查文件头(magic number)
每种文件格式都有“魔数”(magic number),可使用第三方库如 apache tika、jmimemagic、filetypedetector 来检测。
使用 apache tika 示例:
import org.apache.tika.tika; public void validatebytika(multipartfile file) throws ioexception { tika tika = new tika(); string detectedtype = tika.detect(file.getinputstream()); list<string> allowedtypes = list.of("image/jpeg", "image/png", "application/pdf"); if (!allowedtypes.contains(detectedtype)) { throw new illegalargumentexception("文件类型不合法: " + detectedtype); } }
二、实战应用整合到上传接口中(spring boot)
@postmapping("/upload") public responseentity<?> upload(@requestparam multipartfile file) throws ioexception { validatefiletype(file); // 判断 mime 类型 validateextension(file); // 判断文件名后缀 validatebytika(file); // 推荐:更准确安全 // 保存逻辑略... return responseentity.ok("上传成功"); }
三、可配置化(支持配置文件控制允许类型)
application.yml
file: allowed-types: - image/png - image/jpeg - application/pdf
配置类注入
@configurationproperties(prefix = "file") @data public class fileconfig { private list<string> allowedtypes; }
再注入 fileconfig
来校验:
@autowired private fileconfig fileconfig; if (!fileconfig.getallowedtypes().contains(contenttype)) { throw new illegalargumentexception("不支持的文件类型"); }
四、其他建议
场景 | 建议 |
---|---|
前端限制文件选择 | <input accept="image/*"> |
后端强校验必不可少 | 防止绕过前端 |
存储前统一重命名处理 | 防止恶意脚本如 xx.jpg.exe |
加白名单优于黑名单 | 拒绝所有不认识的类型 |
到此这篇关于java实现限制文件上传类型功能的文章就介绍到这了,更多相关java限制文件上传类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论