【发布时间】:2017-01-13 01:42:54
【问题描述】:
我正在使用 NodeJS/Formidable,并尝试保护我的后端以上传图片。
检查文件是否为图像的经典方法是使用这样的正则表达式:
if(!file.name || file.name.match(/\.(jpg|jpeg|png)$/i)) {
console.log("the file is an image");
}else{
console.log("the file is not an image");
}
还有这个:
var fileType = file.type.split('/').pop();
if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ){
console.log("the file is an image");
} else {
console.log( 'incorrect file type: ' + fileType );
}
这是一个很好的检查,但这还不够安全;事实上,如果我将 PDF 重命名为 JPG,浏览器会根据文件的扩展名提供 MIME/type : image/jpg。 这是一个安全问题,因为您可以将 JS 文件或其他任何文件重命名为 JPG 并将其上传到后端文件系统中。
我发现这篇非常有趣的帖子:How to check file MIME type with javascript before upload?
它非常适合客户端检查,但我无法在后端重现。
我想理想的方法是动态分析流并在上传前 4 个字节后检查真正的 MIME 类型。
有什么想法吗?
谢谢!
【问题讨论】:
标签: javascript node.js image-uploading formidable