XMLHttpRequest - event.loaded 和 event.total 值的问题
我使用 XMLHttpRequest 进行文件上传,在浏览器中我有一个进度条,显示图像的大小已经上传。
xhr.upload.addEventListener('progress', onprogressHandler, false);
function onprogressHandler(event) {
resp.innerHTML = event.loaded +' and '+ event.total;
var percent = Math.round((event.loaded / event.total) * 100);
var calc_display = document.getElementById('calc');
calc_display.innerHTML = percent;
};
如果我选择上传图像并发送表单,那么我总是看到相同的 event.loaded
和 event.total
值。 我认为值 event.total
是文件的大小。
我是个新手,没有那么多经验,但我怎么可能总是有相同的价值观呢? (通常约为 2.700.000 kB)
哪里可能有问题?
I use XMLHttpRequest for file upload and in the browser I've a progress bar that show, how big part of image is already uploaded.
xhr.upload.addEventListener('progress', onprogressHandler, false);
function onprogressHandler(event) {
resp.innerHTML = event.loaded +' and '+ event.total;
var percent = Math.round((event.loaded / event.total) * 100);
var calc_display = document.getElementById('calc');
calc_display.innerHTML = percent;
};
If I choose an image for upload and send a form, so I see always the same values of event.loaded
and event.total
.
I think the value event.total
is the size of file.
I am a newbie so I haven't so much of experience, but how is possible I have always the same values? (usually about 2.700.000 kB)
Where could be a problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
进度事件规范 提到进度事件还可以具有布尔值
.lengthComputable
属性。如果进度事件的该属性为 false,我希望event.loaded
和event.total
的值不会反映上传进度。规范规定,如果 XMLHttpRequest 的
Content-Length
标头为,则.lengthComputable
将为 true,并且.total
将反映文件的长度。放。事实证明 XMLHttpRequest 不允许设置Content-长度
- 搜索该锚点下方的Content-Length
。据推测,他们这样做是因为脚本可能会错误计算其发送的数据的长度,而用户代理这样做的可能性要小得多。查看您的服务器正在接收的请求。它们有
Content-Length
标头吗?The progress event spec mentions that a progress event can also have a boolean-valued
.lengthComputable
attribute. If that attribute is false on a progress event, I would expect the values ofevent.loaded
andevent.total
to not reflect the progress of the upload.The specification says that
.lengthComputable
will be true and.total
will reflect the length of the file if theContent-Length
header of the XMLHttpRequest is set. It turns out that XMLHttpRequest will not allow settingContent-Length
-- search forContent-Length
just below that anchor. Presumably they do this because a script might miscalculate the length of the data it is sending and the user agent is far less likely to do so.Look at the requests that your server is receiving. Do they have a
Content-Length
header?如果您上传的视频/图像较小,值可能会相同。您可以通过上传大小超过 70MB 的视频来检查并检查您的加载值和总计值,它应该为您提供不同的总计值和加载值
Values might be same if your uploaded video/image size is small. You can check by uploading video of size more than 70MB and check your loaded and total values, it should give you different values in total and loaded