[英]Progress bar for sending binary files in Websocket
Is there a way to track how many bytes have been sent through a Websocket
connection, so I can show a progress bar. 有没有办法跟踪通过
Websocket
连接发送了多少字节,所以我可以显示一个进度条。
For example I want to send an image. 例如,我想发送图像。 I already know the image size, I just need to have an event on how many bytes have been transferred in the last second for example or something similar.
我已经知道了图像大小,我只需要有一个事件,例如在最后一秒中传输了多少字节,例如类似的东西。
Here is my code 这是我的代码
//html
<input type="file" accept="image/*" id="input">
//js
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileList = this.files;
var connection = new WebSocket('ws://localhost:8080');
connection.binaryType = "arraybuffer";
connection.onopen = () => {
connection.send(fileList[0]);
};
}
I've managed to do this with WebSocket.bufferedAmount
: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket 我已经设法使用
WebSocket.bufferedAmount
执行此操作: https : //developer.mozilla.org/en-US/docs/Web/API/WebSocket
The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
使用send()调用但尚未传输到网络的数据的字节数。 This value resets to zero once all queued data has been sent.
一旦发送了所有排队的数据,该值将重置为零。 This value does not reset to zero when the connection is closed;
连接关闭时,该值不会重置为零; if you keep calling send(), this will continue to climb.
如果你继续调用send(),这将继续攀升。
function sendBinary(binMsg, callback) {
ws.send(binMsg);
if (callback != null) {
var interval = setInterval(function () {
if (ws.bufferedAmount > 0) {
callback(ws.bufferedAmount)
} else {
callback(0)
clearInterval(interval);
}
}, 100);
}
}
}
then I would call the method like this 然后我会这样调用这个方法
var file = fileList[0];
sendBinary(file , function(bytesNotSent){
if(amount==0){
console.log('file sent');
}else{
var loaded = file.size - bytesNotSent;
var percentage = Math.round((loaded * 100) / file.size );
console.log(percentage);
}
});
I've tested this in Chrome 58
, Firefox 53
and Edge 14
and here is my conclusion on how bufferedAmount
is handled: 我已经在
Chrome 58
, Firefox 53
和Edge 14
对此进行了测试,以下是关于如何处理bufferedAmount
结论:
Chrome 58
- constantly updates bufferedAmount
when bytes are sent Chrome 58
- 在发送字节时不断更新bufferedAmount
Firefox 53
- updates bufferedAmount
only when the file is sent ( in Firefox bufferedAmount
has only 2 values file.size
and 0
Firefox 53
- 仅在发送文件时更新bufferedAmount
(在Firefox中bufferedAmount
只有2个值file.size
和0
Edge 14
- updates bufferedAmount
after 1MB of data is sent Edge 14
- 在发送1MB数据后更新bufferedAmount
NOTE : if you send multiple files bufferedAmount
will return the amount of unsent bytes from all those files 注意 :如果发送多个文件,
bufferedAmount
将返回所有这些文件中未发送的字节数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.