我正在使用 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 类型。
有什么想法吗?
谢谢!
最佳答案
有效! 您可以安装类似 readChunk 的模块将文件转换为缓冲区并编写类似的内容:
form.on('file', function(field, file) {
buffer = readChunk.sync(file.path, 0, 4100);
filetype = fileType(buffer);
if(filetype.ext.match(/(jpg|jpeg|png)$/i)) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
}else {
fs.unlink(file.path);
}
});
关于javascript - NodeJS/强大的 : secure the backend for images upload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626124/