gpt4 book ai didi

node.js - 如何从 Node js中的http post请求获取上传进度信息?

转载 作者:可可西里 更新时间:2023-11-01 17:32:26 25 4
gpt4 key购买 nike

我想在使用 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 并执行 response.onEnd。

最佳答案

你只需要添加另一个监听器来处理进度

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

关于node.js - 如何从 Node js中的http post请求获取上传进度信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38768895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com