Image uploading is very common functionality in any programming language. In this article, we will share with you how to preview multiple images before uploading in javascript. sometimes you want to show image preview before it uploads. so, we can check all the images and check before it's uploading in server. preview image before uploading it's main advantages it if we select any wrong images then we change it and then after uploading again.
How to preview multiple images before upload this functionality is very easy to implement in your any platform help of javascript. here you can see how to do it. so, you can use it in your any web application.
Step - 1 Create a project structure
First, we create one simple project structure for how to preview multiple images before upload functionality.
├── imageupload # imageupload (this is your project directory)
│ ├── index.php # index.php (it is your code file)
| |── custom.js # custom.js (write here your image uplod code)
Step - 2 Write code in index.php file
After done create project structure then simply open your index.php
file and put following code into it.
<!DOCTYPE html>
<html>
<head>
<title>Javescript - How to preview multiple images before uplod</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- Jquery CDN JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- custom JS -->
<script src="custom.js"></script>
</head>
<body>
<div class="container">
<input type="file" multiple id="gallery-photo-add">
<div class="col-md-12" class="gallery">
</div>
</div>
</body>
</html>
Step - 3 Write code in custom.js file
Now, write the following code into your custom.js
file.
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
Conclusion
As you can see, create how to preview multiple images before upload in your application is very easy to help of using JavaScript
.
We are hopeful these tutorials help everyone.