Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
showing an img in a div after upload

I am trying to upload an image with javascript and display it in a div but the method I'm using right now is not working. I tried using both an img tag and just setting it as a background-image but both won't show the img in the div but when I inspect the div it shows that the URL has successfully been inserted. Where did I go wrong? Any help is appreciated. Thanks in advance.

const image_input = document.querySelector("#image_input");
image_input.addEventListener("change", function() {
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    const uploaded_image = reader.result;
    $('.imgCon').attr("background-image", `url(${uploaded_image})`);
    $('.imgCon2 img').attr("src", `url(${uploaded_image})`);
  });
  reader.readAsDataURL(this.files[0]);
});
.imgCon {
  position: absolute;
  top: 30%;
  width: 40%;
  height: 40%;
  border-radius: 8px;
  background-color: #000000;
  /* background-size: 100%; */
  background-position: center;
  background-size: cover;
}

.imgCon2 {
  position: absolute;
  top: 30%;
  right: 0%;
  width: 40%;
  height: 40%;
  border-radius: 8px;
  background-color: #000000;
  /* background-size: 100%; */
  background-position: center;
  background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="file" title="" id="image_input" accept="image/png, image/jpg">

<div class="imgCon">
</div>

<div class="imgCon2">
  <img src="" />
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Change to:

$('.imgCon').css("background-image", `url(${uploaded_image})`);
$('.imgCon2 img').attr("src", uploaded_image);

attr will set an attribute on the element i.e <div background-image="url(...)" and src="url(...)" is incorrect.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda