使用express.js和节点上传文件,限制扩展 [英] uploading files using express.js and node, limiting extensions
问题描述
我正在使用express.js和节点处理文件上传,并且基本功能正常工作。我需要的是实施一些安全措施 - 即将上传限制为某些格式(PNG,JPEG)。有没有简单的方法只允许某些格式?它会进入身体解析器吗?
I'm working on handling file uploads using express.js and node, and have the basic functionality working. What I need is to implement some security measures -- namely, to limit uploads to certain formats (PNG, JPEG). Is there an easy way to only allow certain formats? Would it go in the body-parser?
app.use(express.bodyParser({
uploadDir: __dirname + '/public/uploads',
keepExtensions: true }));
app.use(express.limit('4mb'));
我还应该考虑其他任何安全措施?从图像中擦除EXIF数据通常是个好主意?
Are there any other security measures that I should take into account? Is it generally a good idea to wipe EXIF data from the image?
谢谢,
Ben
推荐答案
根据连接的 bodyParser
的文档,任何选项也传递给强大的,它是实际的形式解析。
According to the documentation for connect's bodyParser
, any options are also passed to formidable, which does the actual form parsing.
根据强大的文档,您可以通过自己的 onPart
处理程序:
According to formidable docs, you can pass your own onPart
handler:
incomingForm.onPart(part)
incomingForm.onPart(part)
如果您有兴趣直接访问多部分流,您可以覆盖此方法。这样做将会禁用任何field/file事件处理,否则将导致处理过程的全部负责。
You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any 'field' / 'file' events processing which would occur otherwise, making you fully responsible for handling the processing.
incomingForm.onPart = function(part) {
part.addListener('data', function() {
// ...
});
}
如果您想使用强大的只能为您处理某些部分,您可以这样做:
If you want to use formidable to only handle certain parts for you, you can do so:
incomingForm.onPart = function(part) {
if (!part.filename) {
// let formidable handle all non-file parts
incomingForm.handlePart(part);
}
}
你应该能够这样做:
function onPart(part) {
if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {
this.handlePart(part);
}
}
app.use(express.bodyParser({onPart: onPart});
警告:我没有测试任何这个。
Warning: I haven't tested any of this.
这篇关于使用express.js和节点上传文件,限制扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!