繁体   English   中英

NodeJS / Formidable:保护后端上传图片

[英]NodeJS/Formidable : secure the backend for images upload

我正在使用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并将其上传到后端文件系统中。

我发现这篇文章很有趣: 如何在上传之前使用javascript检查文件MIME类型?

非常适合客户端检查,但是我无法在后端重现此内容。

我想理想的方法是动态分析流并在上传前4个字节后检查真实的MIME类型。

任何想法 ?

谢谢 !

您可能应该使用类似文件类型 npm的程序包,该程序包需要一个缓冲区(至少前4100个字节),并将返回MIME类型和文件扩展名:

const fileType = require('file-type')
fileType(buffer) //=> {ext: 'png', mime: 'image/png'} 

有用 ! 您可以安装诸如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);
    }

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM