Dynamically limit upload file size in Express (node.js)

耗尽温柔 提交于 2019-12-03 22:34:25

问题


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.

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.

Thanks in advance!


回答1:


Express basically uses connect's limit() middleware.

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

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




回答2:


Add limit() before adding bodyParser(), so for example:

app.use(express.limit(100000));
app.use(express.bodyParser({uploadDir: '/tmp', keepExtensions:true}));

This way the uploaded file won't be saved in /tmp when it is too big.



来源:https://stackoverflow.com/questions/10574368/dynamically-limit-upload-file-size-in-express-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!