jQuery Upload Multiple Pictures with Progress Bar Style (DEMO)

  • 2021-07-26 06:15:06
  • OfStack

The following 1 code to share jquery upload a variety of pictures with progress bar style, the specific code is as follows:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>xhr2</title>
</head>
<body>
<div style="text-align: center; margin: 100px">
<input type="file" id="file" name="file" multiple="multiple">
<progress id="uploadprogress" min="0" max="100" value="0">0</progress>
<button onclick="xhr2()">OK</button>
</div>
<script>
function xhr2() {
var xhr = new XMLHttpRequest();// No. 1 1 Step 
// Define form variables 
var file = document.getElementById('file').files;
//console.log(file.length);
// New 1 A FormData Object 
var formData = new FormData(); //++++++++++
formData.append("enctype","multipart/form-data");
// Append file data 
for (i = 0; i < file.length; i++) {
formData.append("file[" + i + "]", file[i]); //++++++++++
}
//formData.append("file", file[0]); //++++++++++
//post Mode 
xhr.open('POST', '/common/doUpload'); // No. 1 2 Steps 
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
var progress = document.getElementById('uploadprogress');
progress.value = progress.innerHTML = complete;
}
};
// Send a request 
xhr.send(formData); // No. 1 3 Steps 
//ajax Return 
xhr.onreadystatechange = function() { // No. 1 4 Step 
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
// Set timeout time 
xhr.timeout = 100000;
xhr.ontimeout = function(event) {
alert(' Request timeout! ');
}
}
</script>
</body>
</html>

Related articles: