SpringBoot后端上传文件类型检测方式
作者:牟云飞 时间:2021-07-02 05:00:04
文件上传大部分通过web前端判断后尾名或者service后端判断后尾名,这种操作具有一定的风险,比如:我可以将一个jsp页面,修改后尾名改成jpg文件进行上传,由于图片预览功能,这个文件会被执行,这时就可以发送用户数据到指定的服务下,窃取用户信息。
本文通过文件流头部判断文件类型
不同的文件具有不同的头部,比如:
不同的文件具有不同的头部信息,以SpringBoot为例,通过 * 拦截文件流进行判断:
1、添加配置文件checkFileHeader.properties
在src/main/resources中增加配置文件checkFileHeader.properties,文件内容:
JPEG=FFD8FF
PNG=89504E47
GIF=47494638
TXT=75736167
PDF=255044462D312E
DOC=D0CF11E0
XML=3C3F786D6C
DOCX=504B0304
APK=504B030414000808
IPA=504B03040A000000
2、编写读取properties文件类
读取checkFileHeader.properties文件内容,用于 * 判断
/**
* 读取文件流头信息
* @author hanjie
*
*/
public class FileHeaderHelper {
private static FileHeaderHelper me ;
private static List<String> headerList ;
private FileHeaderHelper(){}
public static FileHeaderHelper getInstance(){
if(me == null){
me = new FileHeaderHelper() ;
}
return me ;
}
public List<String> getHeaderList(){
if(headerList == null){
headerList = new ArrayList<String>() ;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String classpathResource = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/fileheader.properties";
Properties p = new Properties();
try {
Resource[] res = resolver.getResources(classpathResource) ;
for (Resource re : res) {
p.load(re.getInputStream());
break ;
}
} catch (IOException e) {
e.printStackTrace();
}
for (Map.Entry<Object, Object> item : p.entrySet()) {
headerList.add(item.getValue().toString()) ;
}
}
return headerList ;
}
}
3、编写 *
拦截去中,获取文件流,读取文件流前8个字节,根据需要可以读取更多字节判读,8个字节转成16进制为16个字符串,我这里最长的APK/IPA文件也就16个字节,所以读取8个字节,读取字节后判断是否checkFileHeader.properties文件中字符串
/**
* 文件上传 *
* @author hanjie
*
*/
public class FileHeaderCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// 判断是否为文件上传请求
if (request != null && request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = multipartRequest.getFileMap();
Iterator<String> iterator = files.keySet().iterator();
while (iterator.hasNext()) {
String formKey = (String) iterator.next();
MultipartFile multipartFile = multipartRequest.getFile(formKey);
//String filename = multipartFile.getOriginalFilename();
byte[] file = multipartFile.getBytes() ;
获取字节流前8字节,差不多够了,不行再加
int HEADER_LENGTH = 8 ;
if(file.length>HEADER_LENGTH){
//转成16进制
StringBuilder sb = new StringBuilder();
for(int i=0;i<HEADER_LENGTH;i++){
int v = file[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
sb.append(0);
}
sb.append(hv);
}
boolean isFound = false ;
String fileHead = sb.toString().toUpperCase() ;
List<String> headerList = FileHeaderHelper.getInstance().getHeaderList() ;
for(String header : headerList){
if(fileHead.startsWith(header)){
isFound = true ;
break ;
}
}
if(!isFound){
// throw new BaseRunException("上传文件有异常,已被系统禁止!") ;
System.out.println("----------上传文件有异常,已被系统禁止!头部信息:"+fileHead);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write("上传文件有异常,已被系统禁止!");
return false;
}
}
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
4、配置拦截文件
* 写完了,配置下让它生效,在Configuration中配置 * ,拦截文件流进行判断
@Configuration
public class MyfWebAppConfiguration extends WebMvcConfigurerAdapter {
// * ,拦截文件流
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FileHeaderCheckInterceptor())
.addPathPatterns("/**");
}
// //注册过滤
// @Bean
// public FilterRegistrationBean myFilterRegistration() {
//
// FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(new LoginFilter());
// registration.addUrlPatterns("/serviceInvoke");
// //registration.addInitParameter("paramName", "paramValue");
// registration.setName("loginFilter");
// registration.setOrder(1);
// return registration;
// }
//
//
// //注册servlet
// @Bean
// public ServletRegistrationBean myServletRegistration() {
// ServletRegistrationBean registration = new ServletRegistrationBean(new DownloadServlet());
// registration.addUrlMappings("/download");
// return registration;
// }
}
页面消息提醒已经在printWriter中输出了,根据自己的页面编写显示吧。
来源:https://muyunfei.blog.csdn.net/article/details/90230481
标签:SpringBoot,后端,上传文件,检测
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java创建随机数的四种方式总结
2022-05-11 10:29:17
利用Lambda表达式创建新线程案例
2023-08-26 23:16:00
深入解析Spring Cloud内置的Zuul过滤器
2022-05-16 12:49:04
swing登录注册界面设计
2023-11-24 17:27:21
![](https://img.aspxhome.com/file/2023/5/62825_0s.jpg)
Android Build类的详解及简单实例
2023-07-02 21:12:45
jenkins+Maven从SVN上构建项目的方法
2022-07-09 04:42:37
![](https://img.aspxhome.com/file/2023/2/61582_0s.png)
Android实现腾讯新闻的新闻类别导航效果
2023-07-29 04:17:46
![](https://img.aspxhome.com/file/2023/3/85973_0s.png)
Spring Boot修改启动端口的方法
2022-02-10 05:49:55
java中的this引用及对象构造初始化
2023-03-07 09:38:17
![](https://img.aspxhome.com/file/2023/6/60996_0s.png)
SpringMVC中使用@PathVariable绑定路由中的数组的方法
2023-11-27 14:21:01
![](https://img.aspxhome.com/file/2023/9/61289_0s.png)
JVM内存管理之JAVA语言的内存管理详解
2021-11-01 12:00:10
![](https://img.aspxhome.com/file/2023/5/63105_0s.jpg)
学会IDEA REST Client后就可以丢掉postman了
2023-11-10 15:32:56
![](https://img.aspxhome.com/file/2023/6/62766_0s.png)
详解如何在Spring Security中自定义权限表达式
2023-11-08 05:11:24
![](https://img.aspxhome.com/file/2023/6/58676_0s.jpg)
学习使用Material Design控件(一)
2023-07-27 13:14:06
![](https://img.aspxhome.com/file/2023/3/84743_0s.jpg)
SpringBoot框架中Mybatis-plus的简单使用操作汇总
2022-12-17 19:10:53
Spring MVC+FastJson+hibernate-validator整合的完整实例教程
2021-10-31 13:20:13
Android中如何指定SnackBar在屏幕的位置及小问题解决
2023-08-07 07:56:19
Java8 如何正确高效的使用并行流
2021-06-01 20:29:19
![](https://img.aspxhome.com/file/2023/2/61032_0s.png)
使用jenkins部署springboot项目的方法步骤
2022-06-05 05:18:31
![](https://img.aspxhome.com/file/2023/0/62760_0s.png)
Android中通过样式来去除app的头及界面全屏(备忘)的实现方法
2023-07-30 00:03:23