web worker 包含带有上传进度事件处理程序的 xhr 对象

huangapple go评论50阅读模式
英文:

web worker containing xhr object with upload progress event handler

问题

我正在尝试创建一个工作者(Web Worker),它可以上传附加的文件,并使用事件处理程序来更新我的HTML页面上的进度条。上传功能在工作者中已经正常工作。

我知道Web Worker无法访问DOM对象,而我的所有进度条都在DOM中。所以,我想知道是否有任何解决方法?我想在工作者中进行上传,但我也想要跟踪进度。我将并行上传多个文件,因此每个工作者(上传任务)都将有自己的进度条。
这可行吗?还是应该放弃Web Worker,选择不同的设计?

这是我的工作者中的代码:

onmessage = e => {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xhr.upload ) {
        xhr.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xhr.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xhr upload complete', e]);
        }
    };
    xhr.open('post', url, true);
    xhr.setRequestHeader("Content-Type","multipart/form-data");
    let formData = new FormData();
    formData.append("thefile", e.data.payload);
    xhr.send(formData)
}

我已经准备好了一些事件处理程序,但目前只是用于记录日志。

谢谢。

英文:

I'm trying to create a worker that uploads file attached with event handler that will update progress bar in my html page. the upload is already working fine in the worker.

I know that web worker has no access to DOM objects, which is where all my progress bars are. so, I'm wondering if there's any work around? I want to do the uploads in worker, but I also want the progress tracking. I'll be uploading several file in parallel, so, each worker (upload) will have its own progress bar.
is this doable? or should I let go of web worker altogether and choose different design?

this is what's inside my worker

onmessage = e => {
        var xhr = new XMLHttpRequest();
        xhr.addEventListener('progress', function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
        }, false);
        if ( xhr.upload ) {
            xhr.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
            };
        }
        xhr.onreadystatechange = function(e) {
            if ( 4 == this.readyState ) {
                console.log(['xhr upload complete', e]);
            }
        };
        xhr.open('post', url, true);
        xhr.setRequestHeader("Content-Type","multipart/form-data");
        let formData = new FormData();
		formData.append("thefile", e.data.payload);
        xhr.send(formData)
}

I already prepared some event handler, but currently, it's just logging.

Thanks

答案1

得分: 0

.onmessage 事件包括一个 .source 属性。这是将数据发送回客户端的方法。在进度事件监听器中,您可以添加类似以下的内容:

e.source.postMessage({ uploadName: <unique name>, progress: done });

但要注意,您在 onmessage 处理程序数据和进度事件处理程序中都使用了 e。我建议将它们的名称设置为唯一。

然后,在您的页面中监听消息:

window.addEventListener('message', (data) => {
  // ... 读取 data.progress 并将其发送到页面的正确位置
});
英文:

The onmessage events includes a .source property. This is how you send data back to the client. Inside your progress event listener you would add something like:

e.source.postMessage({uploadName: &lt;unique name&gt;, progress: done});

Watch out, though. You use e as both the onmessage handler data and the progress event handler. I would recommend making the names of the two unique.

Then in your page you listen for the message:

window.addEventListener(&#39;message&#39;, (data) =&gt; {
  // ... read data.progress and send it to the right place on the page
}

huangapple
  • 本文由 发表于 2023年2月7日 01:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定