判断下载文件名是否异常,通常从以下几方面检查:

1. 检查响应头中的文件名
重点查看:
Content-Disposition: attachment; filename="test.pdf"
或:
Content-Disposition: attachment; filename*=UTF-8''%E6%B5%8B%E8%AF%95.pdf
常见异常包括:
- 文件名为空
- 文件名只有扩展名,例如
.pdf - 文件名变成
download、blob、undefined - 中文乱码,例如
æµè¯.pdf - 文件名中包含非法字符
- 文件扩展名与实际文件类型不一致
2. 判断文件名是否合法
以 Java 为例:
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
public static boolean isValidFileName(String fileName) {
if (fileName == null || fileName.trim().isEmpty()) {
return false;
}
String name = fileName.trim();
// 常见默认异常文件名
if (name.equalsIgnoreCase("download")
|| name.equalsIgnoreCase("undefined")
|| name.equalsIgnoreCase("null")
|| name.equals(".")) {
return false;
}
// Windows/Linux 常见非法字符
if (name.matches(".*[\\\\/:*?\"<>|].*")) {
return false;
}
// 防止路径穿越
if (name.contains("..") || name.contains("/") || name.contains("\\")) {
return false;
}
try {
Path path = Paths.get(name);
return path.getFileName().toString().equals(name);
} catch (InvalidPathException e) {
return false;
}
}
3. 判断扩展名是否正常
public static boolean hasExtension(String fileName) {
int index = fileName.lastIndexOf(".");
return index > 0 && index < fileName.length() - 1;
}
例如:
String fileName = "测试文件.pdf";
if (!isValidFileName(fileName) || !hasExtension(fileName)) {
fileName = "download.bin";
}
4. 检查中文乱码
如果服务端返回的是:
filename=%E6%B5%8B%E8%AF%95.pdf
需要 URL 解码:
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
String fileName = URLDecoder.decode(
"%E6%B5%8B%E8%AF%95.pdf",
StandardCharsets.UTF_8
);
如果出现 æµè¯.pdf,通常是 UTF-8 内容被错误地按 ISO-8859-1 解码,需要重新转换编码。
5. 建议的判断顺序
读取 Content-Disposition
↓
解析 filename 或 filename*
↓
URL 解码
↓
去除路径部分
↓
检查空值、非法字符、路径穿越
↓
检查扩展名
↓
异常时使用默认文件名
默认文件名可以根据响应的 Content-Type 生成:
application/pdf → download.pdf
application/zip → download.zip
image/jpeg → download.jpg
如果你说的 HelloWorld 是具体的 Java、Python、Android 或前端下载示例,最好提供相关代码和实际下载出来的文件名,我可以直接帮你定位异常原因。