【问题标题】:Express limit upload speed快递限制上传速度
【发布时间】:2020-12-13 12:57:12
【问题描述】:

express可以限制文件的上传速度吗?

示例:用户有 10Mbp/s 的互联网,我想限制然后只上传他互联网速度的 1/10。

我尝试使用模块 throttle,正如这篇文章所说的 https://stackoverflow.com/a/32340972/13539397,但似乎不起作用。

我的代码:

const Throttle = require("throttle");

route.put("/api/upload", (req, res, next) => {
    req.pipe(new Throttle(1)).pipe(fs.createWriteStream(join(__dirname, "./file.png")));
})

【问题讨论】:

  • 定义 “不起作用” .... 不上传或不限制?有什么错误吗?
  • 不限制,文件为空白或只有字母“c”。这个“c”可能来自我上传到服务器的文件的首字母
  • 我很怀疑这是您可以从服务器端执行的操作。您要减速的是客户端,而不是服务器。

标签: javascript file express upload


【解决方案1】:

改用包express-throttle-bandwidth

var express = require('express')
var throttle = require('express-throttle-bandwidth');
var app = express()
app.use(throttle(100000)); // limits to 100000 bps

app.put("/api/upload", (req, res, next) => {
    req.pipe(fs.createWriteStream(join(__dirname, "./file.png"));
})

由于这限制了实例的连接,所以该实例只用于文件上传

你也可以使用express-throttle

var express = require("express");
var throttle = require("express-throttle");
  
var app = express();
  
// Allow 5 requests at any rate with an average rate of 5/s
app.put("/api/upload",throttle({ "rate": "5/s" }), (req, res, next) => {
    req.pipe(fs.createWriteStream(join(__dirname, "./file.png"));
})

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2011-09-10
    • 2014-06-26
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多