节点XHR文件上载事件

Node XHR file upload events

本文关键字:事件 上载 文件 XHR 节点      更新时间:2023-09-26

考虑一个接收文件上传的ExpressJS应用程序:

app.post('/api/file', function(req, res) {
    req.on('data', function() {
        console.log('asd')
    })
})

我不明白为什么数据事件从未被触发。我还使用bodyParser()中间件,它为每个文件提供了以下对象,这些文件似乎有一些可用的事件,但仍然没有效果:

{
    file: {
        domain: null,
        _events: {},
        _maxListeners: 10,
        size: 43330194,
        path: 'public/uploads/a4abdeae32d56a2494db48e9b0b22a5e.deb',
        name: 'google-chrome-stable_current_amd64.deb',
        type: 'application/x-deb',
        hash: null,
        lastModifiedDate: Sat Aug 24 2013 20: 59: 00 GMT + 0200(CEST),
        _writeStream: {
            _writableState: [Object],
            writable: true,
            domain: null,
            _events: {},
            _maxListeners: 10,
            path: 'public/uploads/a4abdeae32d56a2494db48e9b0b22a5e.deb',
            fd: null,
            flags: 'w',
            mode: 438,
            start: undefined,
            pos: undefined,
            bytesWritten: 43330194,
            closed: true,
            open: [Function],
            _write: [Function],
            destroy: [Function],
            close: [Function],
            destroySoon: [Function],
            pipe: [Function],
            write: [Function],
            end: [Function],
            setMaxListeners: [Function],
            emit: [Function],
            addListener: [Function],
            on: [Function],
            once: [Function],
            removeListener: [Function],
            removeAllListeners: [Function],
            listeners: [Function]
        },
        open: [Function],
        toJSON: [Function],
        write: [Function],
        end: [Function],
        setMaxListeners: [Function],
        emit: [Function],
        addListener: [Function],
        on: [Function],
        once: [Function],
        removeListener: [Function],
        removeAllListeners: [Function],
        listeners: [Function]
    }
}

我想了解如何取得进展并完成活动。

当请求和响应对象可以在Express中访问时,请求已经结束,上传已经完成。因此,data事件不会再触发,因为没有更多的数据可接收(根据Jonathan Ong的评论,可读流已被消耗)。查找文件上传进度的另一种方法是使用中间件,特别是body解析器。

当查看此处的Connect文档时(由于Express是在Connect上构建的),它指出:

defer延迟处理并将Formidable表单对象公开为调用req.form.next()时无需等待表单的"结束"事件。如果需要绑定到"进度"事件,此选项非常有用。

因此,您所要做的就是在初始化主体解析器时将set defer添加为true,然后就可以侦听req.formprogress事件。此处示例:

app.use(express.bodyParser({
  defer: true              
}));
app.post('/upload', function (req, res) {
  req.form.on('progress', function (received, total) {
    var percent = (received / total * 100) | 0;
    console.log(percent + '% has been uploaded.');
  });
  req.form.on('end', function() {
    console.log('Upload completed.');
  });
});

我不认为与express req对象有任何数据事件绑定。你在哪里看到的?

此外,试着在你用来上传的表格上添加这个:

enctype="multipart/form-data"