javascript preview image before upload - javascript

I made a code in the img box in sequence. However, if the if (file.size > 1M) is large, a space occurs in the img box.
How do I get the next image to come in without spaces?
**
javascript preview image before upload
**
<form class="my_form">
<input type="file" id="fileElem" multiple accept="image/*"
onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select Images</label>
<div id="gallery">
<img id="**imgg0**" class="imgg">
<img id="**imgg1**" class="imgg">
<img id="**imgg2**" class="imgg">
<img id="**imgg3**" class="imgg">
<img id="**imgg4**" class="imgg">
</div>
</form>
<script>
function handleFiles(files) {
var files = [...files]
var imgs = document.querySelectorAll('img');
files.forEach(function(file, index){
if(file.size > 1000000){
delete file[index];
} else{
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
var img = **document.getElementById('imgg'+index)**;
img.src = reader.result;
}
}
})
}
</script>
[enter image description here][1]
[1]: https://i.stack.imgur.com/0dJ45.png

Check my solution.
function handleFiles(files) {
var imgs = document.querySelectorAll('img');
//Image element undex
let imgIndex=0;
//Loop through all the images
for(var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onload = function(e) {
var img = document.getElementById('imgg'+imgIndex);
img.src = e.target.result;
imgIndex++;
}
reader.readAsDataURL(files[i]);
}
}
<form class="my_form">
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select Images</label>
<div id="gallery">
<img id="imgg0" width="10%" class="imgg">
<img id="imgg1" width="10%" class="imgg">
<img id="imgg2" width="10%" class="imgg">
<img id="imgg3" width="10%" class="imgg">
<img id="imgg4" width="10%" class="imgg">
</div>
</form>

a simple solution for multi-image previews. This creates img placeholders dynamically for as many pictures selected in file control
<div id="container01"></div>
<input id="filer" type="file" onchange="preview()" multiple="multiple" />
<script>
function preview() {
var element = document.getElementById("container01");
for (var i = 0; i < event.target.files.length; i++) {
var imgi = document.createElement('img'); // variable imgi has i loop counter
imgi.src = URL.createObjectURL(event.target.files[i]);
imgi.style.width = "100px";
imgi.style.height = "100px";
element.appendChild(imgi); // add new preview to container
var space = document.createTextNode(" "); // spacer between imgs
element.appendChild(space); // add space for horizontal preview
// var linebreak = document.createElement('br'); // add line break <br/>
// element.appendChild(linebreak);
}
}
</script>

Related

how to preview images in multiple input type "file"-s

I have this code:
const chosenImage = document.getElementById('chosen_image')
for (const input of document.querySelectorAll('input[type=file]')) {
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
// do stuff
reader.readAsDataURL(input.files[0]);
reader.onload = () => {
chosenImage.setAttribute("src", reader.result);
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name)
}
}
}
}
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_20" onclick="document.getElementById('img_20').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_20' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_21" onclick="document.getElementById('img_21').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_21' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
<div class="section_header">
<figure class="uploaded_image_container">
<img id="chosen_image">
</figure>
<div class="upload_section_outer">
<h6>Text U:</h6>
<div class="upload_section">
<button id="performance_img_19" onclick="document.getElementById('img_19').click()">Upload image</button>
<input type="file" accept="image/png, image/jpg, image/svg" id='img_19' style="display:none">
<label>Upload complete: False</label>
</div>
</div>
</div>
the problem is that it previews only on the first section, but I need to display on every individually for each upload. Additionally the text only changes for the first uploaded image and I have no clue why. Can anyone explain what I am doing wrong?
What you get here is the first chosen_image element, not the second or even the third.
const chosenImage = document.getElementById('chosen_image');
//...
chosenImage.setAttribute("src", reader.result);
//...
It is recommended to use class, So it can be
const chosenImage = document.getElementsByClassName('chosen_image')
const inputs = document.querySelectorAll('input[type=file]');
for(let i=0;i<inputs.length;i++){
input = inputs[i];
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
reader.readAsDataURL(e.target.files[0]);
reader.onload = () => {
chosenImage[i].setAttribute("src", reader.result);
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, e.target.files[0].name)
}
}
}
}
enter image description here
but use for of(it is previewing in the following div ad not in the one the button is pushed)
const chosenImage = document.getElementsByClassName('chosen_image')
let i = 0;
for (const input of document.querySelectorAll('input[type=file]')) {
input.onchange = (e) => {
if (e.target.files.length) {
let reader = new FileReader();
console.log(e.target.nextElementSibling);
// do stuff
reader.readAsDataURL(input.files[0]);
reader.onload = () => {
chosenImage[i].setAttribute("src", reader.result); //edit here
e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name)
}
i++;
}
}
}

Can't get image to display via jQuery when it's being uploaded

Right now I have a url that displays an image when it's loaded. However, there will be an option for this image to be replaced via a form input. I would like the uploaded image to be displayed as soon as it's uploaded so it can be evaluated by the user.
I'm trying to accomplish this via jQuery, but I can't get it to work.
Here's my code:
HTML:
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<img src="..\{{ workshop_info[4] }}" id="output">
</div>
JQuery:
<script>
$(document).ready(function() {
$("#Image").change(function(e){
$("#output").attr("src", e.target.files[0]);
});
});
</script>
You can do this by using FileReader functionality.
I have recreated your example which displays an image when it's loaded
Once i upload my own image by clicking choose file and selected the file. That file will be getting previewed after selection with that image load_images div i created.
As soon as the file is selected i am replace the src of your existing image to the new src which come from readAsDataURL
You can read more about FileReader here in detail.
Working Demo: https://jsfiddle.net/usmanmunir/w5cbgLsk/
Run snippet below to see it working.
$(function() {
//Preview image function
var previewImage = function(image) {
if (image.files) {
//Check all images
var filesAmount = image.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
//Replace images on form upload selected image
$('#output').attr('src', event.target.result)
}
reader.readAsDataURL(image.files[i]);
}
}
};
//Select image and call imagePreview function
$('#Image').on('change', function() {
previewImage(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<div class="load_images">
<img src="http://mandarinazul.co/images/mandarinas.png" id="output">
</div>
</div>
<img src="../yourimage/path/image.jpeg" onclick="previmg()" id="displayimage" />
<input type="file" class="form-control" onchange="selectedimg(this)" id="selectphoto" style="display: none" name="photo">
</div>
function previmg(){
document.querySelector('#selectphoto').click();
}
function selectedimg(e){
if(e.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.querySelector('#displayimage').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]);
}}
OR you can try this too,
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="image has to be load">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}}
try this, both will work charm if any doubt feel free to ask.:-)

JavaScript loading multiple images using For Loop not working

Here is the script. It only loads the last image for some reason. I know it is missing something simple but I just don't know where. I am a newbie to JS. Thanks guys.
<html>
<body>
<div style="display:flex ">
<div style="border:1px solid black"><img id="img0" height="180px">img0</div>
<div style="border:1px solid black"><img id="img1" height="180px">img1</div>
<div style="border:1px solid black"><img id="img2" height="180px">img2</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
<label>Select Image Files:</label>
<input type="file" name="image[]" onchange="onFileSelected(event)" multiple />
<input type="submit" name="submit" value="Upload">
</form>
<script>
function onFileSelected(event) {
for (i = 0; i < event.target.files.length; i++) {
var selectedFile = event.target.files[i];
var reader = new FileReader();
var imgfile = 'img' + i;
var imgtag = document.getElementById(imgfile);
alert(imgtag);
//imgtag.title = selectedFile.name;
reader.onload = function(event) {
imgtag.src = event.target.result;
};
reader.readAsDataURL(selectedFile);
}
}
</script>
</body>
</html>
Your problem is back to FileReader function.FileReader is I/O process and have delay. if you want use FileReader you must use await/sync function.you can see this link and read this document about FileReaderSync .
<html>
<body>
<div style="display:flex ">
<div style="border:1px solid black"><img id="img0" height="180px">img0</div>
<div style="border:1px solid black"><img id="img1" height="180px">img1</div>
<div style="border:1px solid black"><img id="img2" height="180px">img2</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
<label>Select Image Files:</label>
<input type="file" name="image[]" onchange="onFileSelected(this)" multiple />
<input type="submit" name="submit" value="Upload">
</form>
<script>
function onFileSelected(event) {
for (let i = 0; i < event.files.length; i++) {
let selectedFile = event.files[i];
let reader = new FileReader();
let imgtag = document.getElementById('img' + i);
reader.onload = function (readerEvent) {
imgtag.src = readerEvent.target.result;
};
reader.readAsDataURL(selectedFile);
}
}
</script>
</body>
</html>
This should definitely work. Try to use let or const instead of var.

Dynamically multiple input create and image preview

I am trying to make a page where Taking input from a text field, dynamically create multiple file input field. After uploading an image , the image will be previewed in the document.
HTML part
<body>
<input type="number" id="total_member" name="total_member" value="">
Go
<form id="form" runat="server">
</form>
</body>
javascript part
<script type='text/javascript'>
var input_id;
$(window).load(function(){
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#'+'target'+input_id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".image").change(function(){
var target_input = $(this).attr('id');
input_id=target_input;
readURL(this);
});
});
function memberdetails()
{
var number = document.getElementById("total_member").value;
var container = document.getElementById("form");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
var image=document.createElement("img");
image.setAttribute("id","target"+i);
image.setAttribute("style","width:250px; height: 250px");
image.src="../images/default.png";
container.appendChild(image);
var file=document.createElement("input");
file.type="file";
file.setAttribute("id",i);
file.setAttribute("class","image");
container.appendChild(file);
}
}
Instead of the above HTML part if I write
<input type='file' id="1" class="image" />
<img id="target1" src="#" style="width:250px; height: 250px;" />
<input type='file' id="2" class="image" />
<img id="target2" src="#" style="width:250px; height: 250px;" />
Then these two sections work. The input fields which is created by js doesn't work.What's the problem?

Script for load image preview doesn´t work

I create script for show image until upload , how i use 5 input files for upload , the script must let show one image , or preview image for each input file
The Script :
<script>
function handleFileSelect(evt,ids) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
document.getElementById('list'+ids).innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="50"/>'].join('');
///alert("ok"+ids);
};
})(f);
reader.readAsDataURL(f);
}
</script>
HTML CODE
<input type="file" id="files2" />
<output id="list2"></output>
CALLING SCRIPT FOR THIS INPUT FILE ID
<script>
document.getElementById('files2').addEventListener('change', function(){handleFileSelect('','2');},false);
</script>
As you can see i try send vars from handleFileSelect('','2') , but don´t works never and i think the code it´s well , but sure i forget something , i hope here can help me in this issue , thank´s community
The Best Regards
Try this code
$(function () {
var _URL = window.URL || window.webkitURL;
$(".UploadImage").on("change", function () {
var preview = $(this).attr("data-img");
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
document.getElementById(preview).src = _URL.createObjectURL(file);
};
img.src = _URL.createObjectURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="file" data-img="preview1" class="UploadImage" />
<img src="" id="preview1"/>
</div>
<div>
<input type="file" data-img="preview2" class="UploadImage" />
<img src="" id="preview2"/>
</div>
<div>
<input type="file" data-img="preview3" class="UploadImage" />
<img src="" id="preview3"/>
</div>
<div>
<input type="file" data-img="preview4" class="UploadImage" />
<img src="" id="preview4"/>
</div>
It's better if you use CreateObjectURL instead (saves more memory/cpu) it's also faster
var wrapper = document.getElementById('files')
var URL = window.URL || window.webkitURL;
wrapper.addEventListener('change', function(evt){
var input = evt.target
if (input.matches('input[type="file"]') && (input.files || [])[0]) {
var img = new Image
img.width = 50
img.onload = function() {
var output = document.getElementById(input.dataset.for)
output.appendChild(this)
}
img.onerror = function(){
console.log("You uploaded something that is not an image")
}
img.src = URL.createObjectURL(input.files[0])
}
})
output {
display: block;
}
<div id="files">
<!-- Recomend adding accept attribute so you only get images -->
<!-- just made one example -->
<input type="file" data-for="list1" accept="image/*">
<output id="list1"></output>
<input type="file" data-for="list2">
<output id="list2"></output>
<input type="file" data-for="list3">
<output id="list3"></output>
<input type="file" data-for="list4">
<output id="list4"></output>
</div>

Categories