import fs from 'node:fs'
import express from 'express'
import stream from 'progress-stream'
const port = 3000
const app = express()
app.post('/upload', function (req, res) {
const length = req.headers['content-length']
const str = stream({
length,
time: 100,
})
str.on('progress', (process) => {
let percent = process.percentage | 0
// 这里可以打印进度
console.log(`percent`, percent)
})
req.pipe(str).pipe(fs.createWriteStream(`test.mp4`))
req.on('end', async () => {
res.status(200).end('ok')
})
})
server.listen(port, () => {
console.log('server start at ' + port)
})
此时,如果前端直接通过 3000 端口与 express 交互, 流媒体上传的进度可以被正常捕获。
[ 问题 ]:
如果想通过 nginx 服务器转发,应该如何配置呢?
目前简单如下配置,nginx 将在文件完整接收后一次性发送给 express ,也就是说 express 无法捕获上传进度
location / {
client_max_body_size 100m;
proxy_pass http://127.0.0.1:3000/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}