Itzel Bracho Molina
Itzel Bracho Molina

Reputation: 188

How to upload an image in JS and see the preview of the file?

I'm trying to upload an image and that image has a preview. The problem is when I upload the image I get the following error:

Uncaught TypeError: cannot set property ‘innerHTML’ of null

If I remove the following line:

imageContainer.innerHTML="";

this show in the screen:

1 console.log({numOfFiles}); Files Selected

and what I want is for images to appear, what am I doing wrong? I'm following a tutorial and in the tutorial it works for him and it doesn't for me

HTML

<div class="container">
        <input type="file" name="fotosCarro" class="form-control" multiple="" id="file-input" onchange="preview()" accept="image/*" required="">
                <label for="file-input">Upload images</label>
                          <p id="num-of-files">No files chosen</p>
        <div class="images"></div>

</div>

CSS

input[type="file"]{
    display:none;
}


.upload-label{
    display:block;
    position:relative;
    background-color:#025bee;
    color:#fff;
    font-size:18px;
    text-align:center;
    width:300px;
    padding:18px 0;
    margin:auto;
    border-radius:5px;
    cursor:pointer;
}


#images{
    width:90%;
    border:1px solid black;
    position:relative;
    margin:auto;
    display:flex;
    justify-content:space-evenly;
    gap:20px;
    flex-wrap:wrap;
}

figure{
 width:45%;
}


figcaption{
    text-align:center;
    font-size:2.4vmin;
    margin-top:0.5vmin;
}


JS

let fileInput=document.getElementById("file-input");
let imageContainer=document.getElementById("images");
let numOfFiles=document.getElementById("num-of-files");

function preview(){
    imageContainer.innerHTML="";
    console.log({imageContainer});
    numOfFiles.textContent=`${fileInput.files.length}
    console.log({numOfFiles});
    Files Selected`;

    for(i of fileInput.files){
        let reader=new FileReader();
        console.log({reader});
        let figure=document.createElement("figure");
        console.log({figure});
        let figCap=document.createElement("figcaption");
        console.log({figCap});
        figCap.innerText=i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
         let img=document.createElement("img");
         img.setAttribute("src",reader.result);
         figure.insertBefore(img,figCap);
        }
        imageContainer.appendChild(figure);
        reader.readAsDataURL(i);
    }
}

Upvotes: 0

Views: 62

Answers (1)

xxMrPHDxx
xxMrPHDxx

Reputation: 667

Make sure you add the script tag for your javascript code after those elements you want to use or else the document.getElementById(...) won't find them

Also, the last div should have id="images" instead of class

Upvotes: 1

Related Questions