Skip to content

Commit

Permalink
增加对文件上传的验证:过滤掉文件名中的非法字符
Browse files Browse the repository at this point in the history
  • Loading branch information
elunez committed Apr 17, 2023
1 parent e6085ab commit 19dea05
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ static File inputStreamToFile(InputStream ins, String name){
public static File upload(MultipartFile file, String filePath) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
String name = getFileNameNoEx(file.getOriginalFilename());
// 过滤非法文件名
String name = getFileNameNoEx(verifyFilename(file.getOriginalFilename()));
String suffix = getExtensionName(file.getOriginalFilename());
String nowStr = "-" + format.format(date);
try {
Expand Down Expand Up @@ -350,6 +351,44 @@ public static void downloadFile(HttpServletRequest request, HttpServletResponse
}
}

/**
* 验证并过滤非法的文件名
* @param fileName 文件名
* @return 文件名
*/
public static String verifyFilename(String fileName) {
// 过滤掉特殊字符
fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", "");

// 去掉文件名开头和结尾的空格和点
fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", "");

// 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符
int maxFileNameLength = 255;
if (System.getProperty("os.name").startsWith("Windows")) {
maxFileNameLength = 260;
}
if (fileName.length() > maxFileNameLength) {
fileName = fileName.substring(0, maxFileNameLength);
}

// 过滤掉控制字符
fileName = fileName.replaceAll("[\\p{Cntrl}]", "");

// 过滤掉 ".." 路径
fileName = fileName.replaceAll("\\.{2,}", "");

// 去掉文件名开头的 ".."
fileName = fileName.replaceAll("^\\.+/", "");

// 保留文件名中最后一个 "." 字符,过滤掉其他 "."
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");

return fileName;
}


public static String getMd5(File file) {
return getMd5(getByte(file));
}
Expand Down

2 comments on commit 19dea05

@ChinaYC
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

有防止mysql注入那味了, 大佬太强辣

@CFH-Steven
Copy link

@CFH-Steven CFH-Steven commented on 19dea05 May 22, 2023 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.