Any constructive criticism and alternative methods for accomplishing this task are welcomed.
I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM.
To achieve this, I have been using .append()
to insert an image element within the <div id="gallery">
. However, I encountered difficulty in displaying file names along with the corresponding pictures due to the random order of rendering.
Fortunately, I came across a helpful post on HTML5 FileReader how to return result?, where I was able to modify the code to display images instead of 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 query is:
Is there a more efficient way to accomplish this task?
Appreciate your insights, Swift