Images preview before uploading - javascript

So I have here my upload script and it has a function that the user can preview selected images before uploading but my problem is that every time I'll upload all images available for preview it is always the last file chosen.
Heres my code:
<script type="text/javascript">
$(document).ready(function(){
function readURL(input){
if(input.files[0]){
var reader = new FileReader();
reader.onload = function(e){
$(".form-holder").append("<img class='prev' />")
$(".prev").attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#btn_up").change(function(){
readURL(this);
});
});
</script>

Try This Code
HTML
<input id="imgInput" type="file" name="file[]" multiple style="display:none;"/>
<input type="button" onclick="$('#imgInput').click();" value="Choose File" />
<output id="result" ></output>
<div style="margin-top:150px;" id="uploadedcontent"></div>
JS
var ftype = new Array();
$("#imgInput").change(function () {
readURL(this);
});
function readURL(input) {
var files = input.files;
var output = document.getElementById("result");
var count = 0;
var count1 = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
var divid = 'div_' + i;
var spanid = 'span_' + i;
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var picnames = files[count].name;
var mimetypes = picFile.result.split(',');
var mimetype1 = mimetypes[0];
var mimetype = mimetype1.split(':')[1].split(';')[0];
count++;
var div = document.createElement("div");
div.setAttribute('id', 'div_' + count);
div.setAttribute('class', 'divclass');
if (mimetype.match('image')) {
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picnames + "' width='96' height='80' alt='Item Image' style='position:relative;padding:10px 10px 10px 10px;' data-valu='" + mimetype + "'/><span class='boxclose' style='cursor:pointer' id='span_" + count + "'>x</span>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
}
$('body').on('click','.boxclose','',function(e){
var spanid = $(this).attr('id');
var splitval = spanid.split('_');
$('#div_' + splitval[1]).remove();
});
DEMO HERE

Related

How to regenerate DIV when executing the event again with filesInput?

currently working on an administration panel, I want for the user a preview of the image that is about to send after adding a file with an html input element.
Currently the script works, but if you decide to choose a new file with the input again ( the div does not regenerate but duplicates with the new image, leaving the old one still visible.
So I would like the div and the preview to regenerate when we choose an image again with input.
But the question is, how can I do this ?
Thank you all very much in advance for your advice / solutions.
Hope I am understandable, I am a novice and I explain this in my words.
I also send you my greetings from France.
HTML
<div id="result">
<input type="file" id="image" accept="image/*" name="image"/>
Javascript
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("image");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<div class=\"card\" style=\"max-width: 10rem;\"> <img class='card-img-top' src='" + picFile.result + "'" + "title='" + picFile.name + "'/> <div class=\"card-body rgba-black-light p-2\" style=\"text-align:center;\">Nouvelle image </div></div> ";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
OUTPUT.innerHTML = ""
after the output declaration, this set the content of the div "result" to "" (empty)
If you want to regenerate image, you can remove the previous image.
I gave a id to div where image inside and remove it before where you added image.
Here is the snippet
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("image");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
var imageDiv = document.getElementById("imageDiv");//get div element
if(imageDiv!=null){//check div element
imageDiv.remove();}//remove the previous div
div.innerHTML = "<div class=\"card\" style=\"max-width: 10rem;\" id='imageDiv'> <img class='card-img-top' src='" + picFile.result + "'" + "title='" + picFile.name + "'/> <div class=\"card-body rgba-black-light p-2\" style=\"text-align:center;\">Nouvelle image </div></div> ";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}})}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">
<input type="file" id="image" accept="image/*" name="image"/>

Uncaught TypeError: subir_file.forEach is not a function

I have a problem with the conversion object to array..
In the next code read a file json and input de information in a div byte_content
This part of code it's ok..
function leer_json() {
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
subir_file = evt.target.result;
alert(subir_file);
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
}
The second function capture the var subir_file and try the read with the
each but the problem its of diferent type the date..
function sube_json() {
var table = document.getElementById('d_t_json');
subir_file.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.Tipo + '</td>' +
'<td>' + object.Idenfificacion + '</td>' +
'<td>' + object.Periodo_inicial + '</td>' +
'<td>' + object.Periodo_final + '</td>';
table.appendChild(tr);
});
}
please .. how I can change the code .. I need charge the json into talbe of html ..

JS file size test fails on multiple file upload but not on single file upload

I am trying to upload images and before that show which files are invalid based on type and size. When i upload single file with size 5mb it works fine. But when i select multiple files including this 5mb picture my test fails, doesn't detect its size is more than 2. What do you see the problem is ?
JSFIDDLE DEMO
<input type="file" name="file[]" id="image-upload" class="file-input" accept="image/*" multiple>
<div id="img-wrapper"></div>
<hr>
<div id="invalid-images"></div>
<style type="text/css">
.invalid-img-thumbnail{
width: 100px;
height:100px;
border: 2px solid red;
}
.thumbnail{
width: 100px;
height:100px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
var valid_extensions = ["jpg", "jpeg", "png", "gif"];
$("#image-upload").change(function() {
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = (function(name, event) {
var img = event.target.result; //image preview
var extension = name.split('.')[name.split('.').length - 1].toLowerCase(); //get file extension
if(valid_extensions.indexOf(extension)===-1 || file.size > (2000 * 1024)){ //if extension is valid image extension type and size is less that 2mb
$('#invalid-images').append(
"<img class='invalid-img-thumbnail' src='" + img + "'" + "title='" + name + "'/>");
}else{
$('#img-wrapper').append(
"<img class='thumbnail' src='" + img + "'" + "title='" + name + "'/>");
console.log('\n'+file.size);
}
}).bind(reader, file.name);
reader.readAsDataURL(file);
}
});
</script>
You need to add file.size to the function binding. Otherwise, when you use file.size in the callback function, it's referring to the last file in the loop.
$("#image-upload").change(function() {
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = (function(name, size, event) {
var img = event.target.result; //image preview
var extension = name.split('.')[name.split('.').length - 1].toLowerCase(); //get file extension
if(valid_extensions.indexOf(extension)===-1 || size > (2000 * 1024)){ //if extension is valid image extension type and size is less that 2mb
$('#invalid-images').append(
"<img class='invalid-img-thumbnail' src='" + img + "'" + "title='" + name + "'/>");
}else{
$('#img-wrapper').append(
"<img class='thumbnail' src='" + img + "'" + "title='" + name + "'/>");
console.log('\n'+size);
}
}).bind(reader, file.name, file.size);
reader.readAsDataURL(file);
}
});
DEMO

View multiple browsed images with unique ID

After searching in stackoverflow, finally I found a code that can browse multiple images and preview them one-by one. However, when I inspected the element in the browser, all the id for each image is same.
So, I hope anyone can help me how to modify this code so that each image which is browsed has its own unique id.
Here is the fiddle:
And
Here is the html form:
<input id="imgInput" type="file" name="file[]" multiple style="display:none;"/>
<input type="button" onclick="$('#imgInput').click();" value="Choose File" />
<output id="result" ></output>
<div style="margin-top:150px;" id="uploadedcontent"></div>
Here is the JS code:
var ftype = new Array();
$("#imgInput").change(function () {
readURL(this);
});
function readURL(input) {
var files = input.files;
var output = document.getElementById("result");
var count = 0;
var count1 = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
var divid = 'div_' + i;
var spanid = 'span_' + i;
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var picnames = files[count].name;
var mimetypes = picFile.result.split(',');
var mimetype1 = mimetypes[0];
var mimetype = mimetype1.split(':')[1].split(';')[0];
count++;
var div = document.createElement("div");
div.setAttribute('id', 'div_' + count);
div.setAttribute('class', 'divclass');
if (mimetype.match('image')) {
div.innerHTML = "<img id='img_" + count + "' class='thumbnail' src='" + picFile.result + "'" +
"title='" + picnames + "' width='96' height='80' alt='Item Image' style='position:relative;padding:10px 10px 10px 10px;' data-valu='" + mimetype + "'/><span class='boxclose' style='cursor:pointer' id='span_" + count + "'>x</span>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
}
It just needs the count used on the div, added to the img just a tiny change see fiddle below
http://jsfiddle.net/ekzfz9ck/4/
var ftype = new Array(), count1=0;
$("#imgInput").change(function () {
readURL(this);
});
function readURL(input) {
var files = input.files;
var output = document.getElementById("result");
var count = 0;
var count1 = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
var divid = 'div_' + i;
var spanid = 'span_' + i;
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var picnames = files[count].name;
var mimetypes = picFile.result.split(',');
var mimetype1 = mimetypes[0];
var mimetype = mimetype1.split(':')[1].split(';')[0];
count++;
count1++;
var div = document.createElement("div");
div.setAttribute('id', 'div_' + count);
div.setAttribute('class', 'divclass');
if (mimetype.match('image')) {
// below we add the id using the count used for the div;
div.innerHTML = "<img id='img_" + count1 + "' class='thumbnail' src='" + picFile.result + "'" +
"title='" + picnames + "' width='96' height='80' alt='Item Image' style='position:relative;padding:10px 10px 10px 10px;' data-valu='" + mimetype + "'/><span class='boxclose' style='cursor:pointer' id='span_" + count + "'>x</span>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
}

Reset button for each preview image

I don't want to create a remove button; for each images which are previewed before they are going to be uploaded. The reason is because each image has a unique id, so that if it uses a remove button it will mess up the id arrangement when one of the images is removed.
I know this is a little complicated.
How to create a reset button for each images? So, when the user click the reset button, it will open the window of the user computer to pick the new image, and the id of the new picked image is still the same as before.
Here is my code:
var ftype = new Array(), count1 = 0;
$("#imgInput").change(function () {
readURL(this);
});
function readURL(input) {
var files = input.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
var divid = 'div_' + i;
var spanid = 'span_' + i;
var count = 0;
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var picnames = files[count].name;
var mimetypes = picFile.result.split(',');
var mimetype1 = mimetypes[0];
var mimetype = mimetype1.split(':')[1].split(';')[0];
count++;
count1++;
var div = document.createElement("div");
div.setAttribute('id', 'div_' + count);
div.setAttribute('class', 'divclass');
if (mimetype.match('image')) {
div.innerHTML = "<img id='img_" + count1 + "' class='thumbnail' src='" + picFile.result + "'" +
"title='" + picnames + "' width='96' height='80' alt='Item Image' style='position:relative;padding:10px 10px 10px 10px;' data-valu='" + mimetype + "'/>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
}
MY FIDDLE

Categories