如何从节点js中的http post请求获取上传进度信息?

时间:2016-08-04 13:35:17

标签: node.js http

我想在使用node js http的http post请求期间获取上传进度信息。 我的代码很简单,但它可以工作,但只有在出现错误或上传完成时才会通知我。 但是我需要向用户显示一个进度条,为此我需要每隔一秒检查一次进度。 基本上我需要上传速度以及在给定时间上传了多少文件。

const http = require('http');
const fs = require('fs');
const FormData = require('form-data');

function myUploadFunction(authToken,uploadPath, file) {

    const form = new FormData();
    form.append('file', fs.createReadStream(file.path));
    form.append('filename', file.name);
    form.append('parent_dir', '/');
    const requestHeaders = {
        Accept: '*/*',
        Authorization: `Token ${authToken}`,
    };
    const options = {
        host: 'myHost',
        port: 'myPort',
        path: uploadPath,
        method: 'POST',
        headers: requestHeaders,
    };
    form.submit(options, (error, response) => {

        response.setEncoding('utf8');
        response.on('data', (chunk) => {
            // this code runs only when the upload is completed and the server only send some info about the file. And only if this info is large it will send it in chunks
            logger.debug(`BODY: ${chunk}`);
        });
        response.on('end', () => {
            logger.debug('No more data in response.');
        });
    });
}

当我上传文件时,在上传完成之前没有任何反应,然后我得到响应并执行response.onData和afetr,即response.onEnd。

1 个答案:

答案 0 :(得分:1)

您只需要添加另一个侦听器来处理进度

    form.on('progress', (bytesReceived, bytesExpected)  => {
        logger.warn('progress bytesReceived: ', bytesReceived);
        logger.warn('progress bytesExpected: ', bytesExpected);
    });