gpt4 book ai didi

javascript - HTML5 中的 javascript 上传进度显示

转载 作者:行者123 更新时间:2023-11-30 20:56:14 24 4
gpt4 key购买 nike

我对 js 和 html 编程很陌生。我正在使用以下代码制作一个显示文件上传进度的进度条。但它不适用于 tryit 编辑器

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
.progress-wrapper {
width:100%;
}
.progress-wrapper .progress {
background-color:green;
width:0%;
padding:5px 0px 5px 0px;
}
</style>
<script>
function postFile() {
var formdata = new FormData();

formdata.append('file1', $('#file1')[0].files[0]);

var request = new XMLHttpRequest();

request.upload.addEventListener('progress', function (e) {
var file1Size = $('#file1')[0].files[0].size;

if (e.loaded <= file1Size) {
var percent = Math.round(e.loaded / file1Size * 100);
$('#progress-bar-file1').width(percent + '%').html(percent + '%');
}

if(e.loaded == e.total){
$('#progress-bar-file1').width(100 + '%').html(100 + '%');
}
});

request.open('post', '/echo/html/');
request.timeout = 45000;
request.send(formdata);
}
</script>
</head>
<form id="form1">
<input id="file1" type="file" />
<div class="progress-wrapper">
<div id="progress-bar-file1" class="progress"></div>
</div>
<button type="button" onclick="postFile()">Upload File</button>
</form>
</html>

我也在我的本地系统上试过,它在这里也不起作用。我做错了什么?请告诉我如何改进代码。我想显示一个进度条,它显示使用 ajax 调用的文件上传百分比。

最佳答案

没有JQuery的版本

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
.progress-wrapper {
width:100%;
}
.progress-wrapper .progress {
background-color:green;
width:0%;
padding:5px 0px 5px 0px;
}
</style>
<script>
function postFile() {
var formdata = new FormData();

formdata.append('file1', document.getElementById('file1').files[0]);

var request = new XMLHttpRequest();

request.upload.addEventListener('progress', function (e) {
var file1Size = document.getElementById('file1').files[0].size;
console.log(file1Size);

if (e.loaded <= file1Size) {
var percent = Math.round(e.loaded / file1Size * 100);
document.getElementById('progress-bar-file1').style.width = percent + '%';
document.getElementById('progress-bar-file1').innerHTML = percent + '%';
}

if(e.loaded == e.total){
document.getElementById('progress-bar-file1').style.width = '100%';
document.getElementById('progress-bar-file1').innerHTML = '100%';
}
});

request.open('post', '/echo/html/');
request.timeout = 45000;
request.send(formdata);
}
</script>
</head>
<form id="form1">
<input id="file1" type="file" />
<div class="progress-wrapper">
<div id="progress-bar-file1" class="progress"></div>
</div>
<button type="button" onclick="postFile()">Upload File</button>
</form>
</html>

关于javascript - HTML5 中的 javascript 上传进度显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638314/

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