article

Monday, April 4, 2022

jQuery Preview Multiple Images

jQuery Preview Multiple Images

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//index.html
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Preview Multiple Images</title>
    <style>
        .hidden{
            display:none;
        }
        #preview{
            margin-top:50px;
        }      
        #preview img {
            margin:10px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <h2><center>jQuery Preview Multiple Images </center></h2>
        <input type="file" name="file" id="file" class="hidden" multiple>
        <center><button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button></center>
        <div id="preview"></div>   
    </div>
</div>
<script>
$(document).ready(function(){
    $('#filebutton').click(function(){
        $('#file').click();
    });
 
    $('#file').change(function(){
 
        var name = $(this).val().split('\\').pop();
        var file = $(this)[0].files;
        if(name != ''){
            if(file.length >=2){
                $('#filetext').html(file.length + ' files ready to upload');
            }
            else{
                $('#filetext').html(name);
            }
        }
    });
 
    $('#file').on("change", previewImages);
});
 
function previewImages() {
 
  var $preview = $('#preview').empty();
  if (this.files) $.each(this.files, readAndPreview);
 
  function readAndPreview(i, file) {
     
    if (!/\.(jpe?g|png|gif)$/i.test(file.name)){
      return alert(file.name +" is not an image");
    } // else...
     
    var reader = new FileReader();
 
    $(reader).on("load", function() {
      $preview.append($("<img>", {src:this.result, height:200}));
    });
 
    reader.readAsDataURL(file);
     
  }
 
}
</script>
</body>
</html>

Related Post