ladjs / superagent

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
https://ladjs.github.io/superagent/
MIT License
16.58k stars 1.33k forks source link

The problem of progress event when upload file #1610

Open yiyexingyu opened 3 years ago

yiyexingyu commented 3 years ago

I'm trying to use the .on('progress', cb) method for listening the progress of file upload.But smothing worng hapend when I pass different type param to the .attach.The progrss is fine when pass the file path, but event.percent shows 100% and it took minutes before uploading to server when pass Buffer.

Relevant versions:

Pass a file path: (the file total size is 82.3MB)

const filePath = 'path/to/the/file';
superagent.post(uploadUrl)
        .attach('upload', filePath, path.basename(filePath))
       .on('progress', event =>{
               console.log(event.loaded)
       })
       .end((err, res) => {
           if(!err) console.log(res.status)
       })

result:

181
65717
131253
196789
262325
327861
393397
458933
524469
590005
655541
721077
786613
852149
917685
983221
.....
.....
85328053
85393589
85459125
85524661
85590197
85655733
85721269
85786805
85852341
85917877
85983413
86048949
86114485
86180021
86245557
86302755
86302757
86302858
86302859
86302861
86302967
86302969
86303027
200

The loaded is increase slowly。When loaded = totalSize,upload action is finished。

Pass Buffer

const filePath = 'path/to/the/file';
superagent.post(uploadUrl)
        .attach('upload', fs.readFileSync(filePath), path.basename(filePath))
       .on('progress', event =>{
               console.log(event.loaded)
       })
       .end((err, res) => {
           if(!err) console.log(res.status)
       })

result

181
86302755
86302757
86302858
86302859
86302861
86302967
86302969
86303027
// Wait half a minute here
200

The loaded increase so fask. Loaded = totalSize and it took minutes before uploading to server.