patternjavascriptMinor
Uploading multiple images
Viewed 0 times
imagesuploadingmultiple
Problem
I have this code which works for uploading multiple files (images). However, it seems inefficient due to having to a function for every single file upload (for 2 uploads, but there will be about 12 in total).
Then...
function readURL1(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
jQuery('#div1').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
function readURL2(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
jQuery('#div2').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}Then...
jQuery("#img1").change(function(){
readURL1(this);
});
jQuery("#img2").change(function(){
readURL2(this);
});Solution
No need for a loop. The only difference between the functions is the target image (I assume it's an image, since DIVs don't have a
Add those data attributes to the HTML:
As you may notice the id of the input fields have gone. Instead of assigning them each their own separate event handler, assign one handler for all (or use a class):
srcattribute), so change the function to get the target from an data attribute of the input field:function readURL(input) {
if (input.files && input.files[0]) {
var image = jQuery(input).data('image-target');
var reader = new FileReader();
reader.onload = function (e) {
jQuery(image).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}Add those data attributes to the HTML:
Image 1:
Image 2: As you may notice the id of the input fields have gone. Instead of assigning them each their own separate event handler, assign one handler for all (or use a class):
jQuery("input[type=file]").change(function() {
readURL(this);
});Code Snippets
function readURL(input) {
if (input.files && input.files[0]) {
var image = jQuery(input).data('image-target');
var reader = new FileReader();
reader.onload = function (e) {
jQuery(image).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}Image 1: <input type="file" data-image-target="#div1">
Image 2: <input type="file" data-image-target="#div2">jQuery("input[type=file]").change(function() {
readURL(this);
});Context
StackExchange Code Review Q#52250, answer score: 2
Revisions (0)
No revisions yet.