Using the FileReader API (English) , you can read the address that is in input
of type file
and collect the binary data to later inject on the page:
Function
In the function below, we are reading the content of input
of type file
and after its completion we create a new DOM element img
to which we assign the read data. Finally, we attach the element to the current page, just after the input
in question.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img = $('<img/>').attr('src', e.target.result);
$(input).after($img);
}
reader.readAsDataURL(input.files[0]);
}
}
Your practical case
For your practical case, in addition to the function above, you need a small change to the code you have, so that the use of the API is also performed on the elements you create dynamically.
Where you are attaching the event change
:
$('input[type=file]').on("change", function(){
verificaMostraBotao();
});
Let's change to a delegation, in this case from body
:
$('body').on("change", "input[type=file]", function(){
verificaMostraBotao();
readURL(this);
});
Ensuring that new input
created by your role can preview the chosen file.
Final Code
The all-together code stays compliant as seen below and in JSFiddle:
Example running on JSFiddle
HTML
<input type="file">
<input type="button" class="hide" value="Adicionar outro">
jQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img = $('<img/>').attr('src', e.target.result);
$(input).after($img);
}
reader.readAsDataURL(input.files[0]);
}
}
function verificaMostraBotao() {
$('input[type=file]').each(function(index){
if ($('input[type=file]').eq(index).val() != "")
$('.hide').show();
});
}
$('body').on("change", "input[type=file]", function() {
verificaMostraBotao();
readURL(this);
});
$('.hide').on("click", function() {
$(document.body).append($('<input />', {type: "file" }).change(verificaMostraBotao));
$('.hide').hide();
});
Credits of the readURL
function, in its simplest form, for @Ivan Baev in SOEN in this answer .