在Express(node.js)中动态限制上传文件大小

问题描述:

我正在开发一个简单的应用程序,允许用户上传他们的内容。我想限制Express将接受的文件大小。我知道我可以使用

I'm developing a simple app that will allow users to upload their content. I want to limit the file size which Express will accept. I know I can use

app.use(express.limit('2mb'));

但我想要动态更改限制。某些用户将有更高的限制。

but I want to change the limit dynamically. Certain users will have higher limits.

最好的解决方案是FIRST检查 content-length 标题和THEN如果文件大小低于限制,则开始解析上传,但Express会自动将文件上传到磁盘(/ tmp目录)。所以如果有人发送1GB的文件,这个文件将被解析并保存到磁盘,即使我不想允许。

The best solution would be to FIRST check the content-length header and THEN start to parse the upload if file size is below the limit but Express automatically saves file uploads to disk (/tmp directory). So if someone sends 1GB file, this file will be parsed and saved to disk even when I don't want to allow that.

提前感谢!

Express基本上使用connect的limit()中间件。

Express basically uses connect's limit() middleware.

所以你可能想写你自己的中间件,而不是使用默认的limit()。

So you might want to write you own middleware instead of using the default limit().

你可以先看看这里的限制()的源代码 https://github.com/senchalabs/connect/blob/2.24.2/lib /middleware/limit.js#L40

You can start by looking at the source code for limit() here https://github.com/senchalabs/connect/blob/2.24.2/lib/middleware/limit.js#L40