在 Express (node.js) 中动态限制上传文件大小 [英] Dynamically limit upload file size in Express (node.js)

查看:47
本文介绍了在 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.

最好的解决方案是首先检查 content-length 标头,然后如果文件大小低于限制,则开始解析上传,但 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().

您可以从这里查看 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

这篇关于在 Express (node.js) 中动态限制上传文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆