javascript - 上传文件 Node.js Express put 方法

标签 javascript node.js express file-upload

我正在尝试使用 XMLHttpRequest 上传文件,我正在拆分文件并且 chunk_size 是 10KB。 在我使用的服务器上

app.route('/upload/').put(function(req, res, next) {

    var  buff =req._readableState.buffer[0];
    console.log('Buffer length: ' + buff.length);   
}

console.log:“缓冲区长度:10240”

我正在写文件:

fs.write(fd,buff,0,buff.length,pos,function(){}

我没有使用 busboy、multer 或 body-parser 一切都像一个魅力。

然后我将 chunk_size 更改为 100KB,客户端发送 100KB,我检查了 Content-Length。

但是服务器正在接收 31972 字节,有时是 64061 字节。

console.log:“缓冲区长度:31972”

不知道发生了什么,我们将不胜感激。

最佳答案

作为 _readableState 的前导下划线提示,这不是外部 API,不建议使用。这是 the docs on streams 的摘录:

Both Writable and Readable streams will buffer data on an internal object which can be retrieved from _writableState.getBuffer() or _readableState.buffer, respectively.

...

The purpose of streams, especially with the stream.pipe() method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory.

所以在这种情况下发生的事情是,一些数据被放入流中的内部队列中,等待消费。

可读流应该使用 stream.read() 并监听 data 事件,或者,在这种情况下,这应该是最简单的方法,使用pipe 方法,如下所示:

req.pipe(fs.createWriteStream("some/path"));

参见 docs on createWriteStream .

关于javascript - 上传文件 Node.js Express put 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35521135/

相关文章:

JavaScript匿名函数模拟lambda演算中的算术,结果返回 `undefined`

javascript - 编辑文本框时如何设置文本颜色

ios - Socket.io 通过套接字对象在服务器上获取事件字符串

javascript - 在 Docker 中使用本地卷共享运行 Gatsby

node.js - 如何在每次创建文章并将其保存在数据库中时生成 slug?

javascript - 云HTTPS函数: returning a Promise which is inside a Promisee

javascript - 在 react-redux 中定义函数很奇怪

javascript - 在 map 函数内从 Mongoose 获取文档会返回 Promise 待处理以及数据

node.js - SocketIO 发射不会在快速路线内触发

node.js - SailsJS 使用一个 Controller 操作调用两个 Service 方法