I do welcome constructive criticism and suggestions for different methods of completing this task.
I'm trying to write some jQuery that will allow users to preview a file or multiple files within the current window without the DOM being reloaded.
To achieve this, the simplest way I know, to .append()
an image element within <div id="gallery">
. I found myself struggling to get the file names to be displayed along with the correct picture, the main issue was that the pictures rendered in no particular order (probably whichever file was smallest was rendered first).
Luckily I stumbled across this post, HTML5 FileReader how to return result? and managed to adapt the code so that it rendered the picture instead of the base64 encoding.
$(function(){
$('#file_input').change(function(e){
var files = $(this.files)
$(this.files).each(function(i){
readFile(files[i], function(e) {
var imageSrc = e.target.result
$('#output_field').append('<h4>'+files[i].name+'</h4><img class="preview-thumbs" id="gallery-img" src="' + imageSrc + '">');
})
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsDataURL(file);
}
});
.preview-thumbs {display: block; padding: 10px 0px; width: 250px;}
.thumb-containers {}
#gallery>.img-container {display: inline-block; border: 3px solid #243d51; padding: 5px; width: 350px; border-radius: 20px; text-align: center;}
h4 {color: red; font-size: 20px; font-weight: bold;}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="file" id="file_input" class="foo" multiple/>
<div id="output_field" class="foo"></div>
My question here is:
Is there (if any) better way of completing this task?
Cheers in advance, Swift