当前位置: 首页 > news >正文

Spring Boot 校验用户上传的图片文件

图片上传是现代应用中非常常见的一种功能,也是风险比较高的一个地方。恶意用户可能会上传一些病毒、木马。这些东西不仅严重威胁服务器的安全还浪费了带宽,磁盘等资源。所以,在图片上传的接口中,一定要对用户上传的文件进行严格的校验

本文介绍了 2 种对图片文件进行验证的方法可供你参考。

一、文件后缀校验

通过文件后缀(也就是文件扩展名,通常用于表示文件的类型),进行文件类型校验这是最常见的做法。

图片文件的后缀类型有很多,常见的只有:jpgjpeggifpngwebp。我们可以在配置或者代码中定义一个“允许上传的图片后缀”集合,用于校验用户上传的图片文件。

package cn.springdoc.demo.web.controller;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/upload")
public class UploadController {// 允许上传的图片类型的后缀集合static final Set<String> imageSuffix = Set.of("jpg", "jpeg", "gif", "png", "webp");@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public ResponseEntity<String> upload (@RequestParam("file") MultipartFile file ) throws IllegalStateException, IOException{// 文件的原始名称String fileName = file.getOriginalFilename();if (fileName == null) {return ResponseEntity.badRequest().body("文件名称不能为空");}// 解析出文件后缀int index = fileName.lastIndexOf(".");if (index == -1) {return ResponseEntity.badRequest().body("文件后缀不能为空");}String suffix = fileName.substring(index + 1);if (!imageSuffix.contains(suffix.trim().toLowerCase())) {return ResponseEntity.badRequest().body("非法的文件类型");}// IO 到程序运行目录下的 public 目录,这是默认的静态资源目录Path dir = Paths.get(System.getProperty("user.dir"), "public");if (!Files.isDirectory(dir)) {// 创建目录Files.createDirectories(dir);}file.transferTo(dir.resolve(fileName));// 返回相对访问路径return ResponseEntity.ok("/" + fileName);}
}

如上,代码很简单。先是获取客户端文件的名称,再从名称获取到文件的后缀。确定是合法文件后再 IO 到本地磁盘。

二、使用 ImageIO 校验

由于文件的后缀是可编辑的,恶意用户可以把一个 exe 文件的后缀改为 jpg 再上传到服务器。于是这种情况下,上面的这种校验方式就会失效,恶意文件会被 IO 到磁盘。

在基于上面的方法进行校验后,我们可以先把文件 IO 到临时目录,再使用 ImageIO 类去加载图片文件,如果 Images 加载的文件不是图片,则会返回 null

package cn.springdoc.demo.web.controller;import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.UUID;import javax.imageio.ImageIO;import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/upload")
public class UploadController {// 允许上传的图片类型的后缀集合static final Set<String> imageSuffix = Set.of("jpg", "jpeg", "gif", "png", "webp");@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file)throws IllegalStateException, IOException {// 文件的原始名称String fileName = file.getOriginalFilename();if (fileName == null) {return ResponseEntity.badRequest().body("文件名称不能为空");}// 解析出文件后缀int index = fileName.lastIndexOf(".");if (index == -1) {return ResponseEntity.badRequest().body("文件后缀不能为空");}String suffix = fileName.substring(index + 1);if (!imageSuffix.contains(suffix.trim().toLowerCase())) {return ResponseEntity.badRequest().body("非法的文件类型");}// 获取系统中的临时目录Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));// 临时文件使用 UUID 随机命名Path tempFile = tempDir.resolve(Paths.get(UUID.randomUUID().toString()));// copy 到临时文件file.transferTo(tempFile);try {// 使用 ImageIO 读取文件if (ImageIO.read(tempFile.toFile()) == null) {return ResponseEntity.badRequest().body("非法的文件类型");}// 至此,这的确是一个图片资源文件// IO 到运行目录下的 public 目录Path dir = Paths.get(System.getProperty("user.dir"), "public");if (!Files.isDirectory(dir)) {// 创建目录Files.createDirectories(dir);}Files.copy(tempFile, dir.resolve(fileName));// 返回相对访问路径return ResponseEntity.ok("/" + fileName);} finally {// 始终删除临时文件Files.delete(tempFile);}}
}

这种方式更为严格,不但要校验文件后缀还要校验文件内容。弊端也显而易见,会耗费更多的资源!

1、ImageIO.read 方法

最后说一下 ImageIO.read 方法,它会从系统中已注册的 ImageReader 中选择一个 Reader 对图片进行解码,如果没有 Reader 能够解码文件,则返回 null。也就是说,如果上传的图片类型,在系统中没有对应的 ImageReader 也会被当做是“非法文件”。

例如:webp 类型的图片文件,ImageIO.read 就读取不了,因为 JDK 没有预置读取 webp 图片的 ImageReader

要解决这个问题,可以添加一个 webp-imageio 依赖。

<!-- https://mvnrepository.com/artifact/org.sejda.imageio/webp-imageio -->
<dependency><groupId>org.sejda.imageio</groupId><artifactId>webp-imageio</artifactId><version>0.1.6</version>
</dependency>

webp-imageio 库提供了 webp 图片的 ImageReader 实现,并以 SPI 的形式注册到了系统中,不要写其他任何代码就可以成功读取。

http://www.lryc.cn/news/227639.html

相关文章:

  • 【springboot配置项动态刷新】与【yaml文件转换为java对象】
  • JS移动端触屏事件
  • C语言——打印1000年到2000年之间的闰年
  • 【Linux】【驱动】设备树下的paltform总线
  • 洛谷 NOIP 2023 模拟赛-汪了个汪-题解
  • 洛谷 NOIP 2023 模拟赛 P9836 种树
  • 链表经典OJ题(链表回文结构,链表带环,链表的深拷贝)
  • AD教程 (十三)常见CHIP封装的创建
  • 从0到1实现一个前端监控系统(附源码)
  • 第7章-使用统计方法进行变量有效性测试-7.2-方差分析
  • 【MongoDB】索引 – 文本索引(用权重控制搜索结果)
  • Git 入门使用
  • 如何写好接口自动化测试脚本
  • openEuler编译安装nmon性能监控工具及可视化分析工具
  • 96 前缀树Trie
  • “第六十六天”
  • MYSQL5.7和MYSQL8配置主从
  • springboot苍穹外卖实战:九、小程序微信登录代码开发+商品浏览
  • 【MySQL系列】 第二章 · SQL(下)
  • SpringBoot_01
  • 【OS】AUTOSAR架构下多核通信
  • 从Docker Hub获取镜像和创建容器
  • 江西开放大学引领学习新时代:电大搜题助力学子迈向成功
  • 入门指南:Docker的基本命令
  • nvdiffrast的MeshRenderer
  • APISIX源码安装问题解决
  • 基于SSM和vue的在线购物系统
  • 力扣100题——子串
  • 自然语言处理中的文本聚类:揭示模式和见解
  • C/C++内存管理——“C++”