1. 工具类jar包
- 这里使用gradle,不是maven
- 检查文件类型的工具包,文档链接
implementation 'cn.hutool:hutool-all:5.7.12'
2. 配置文件
# 文件大小
spring.servlet.multipart.max-file-size=5MB
# 请求大小
spring.servlet.multipart.max-request-size=10MB
3. 检查文件类型
- 如果工具类中不存在你需要限制的文件类型(比如苹果手机的图片格式heic),则需要提前检查出文件的字节头(使用bytesToHexString方法),再添加到工具类的Map中
package com.example.fisher.gradledemo.controller;
import cn.hutool.core.io.FileTypeUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.Set;
@RestController
public class CheckFileType {
@PostMapping("/checkFileType")
public boolean checkFileType(@RequestParam("file") MultipartFile multipartFile) throws Exception {
System.out.println(bytesToHexString(multipartFile.getBytes()).substring(0, 20));
Set<String> fileType = Set.of("jpg", "png", "heic");
FileTypeUtil.putFileType("000000286674", "heic");
String type = FileTypeUtil.getType(multipartFile.getInputStream());
System.out.println(type);
return Optional.ofNullable(type).map(fileType::contains).orElse(false);
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}