1
resposta

[Dúvida] Como inserir o SRC a partir do input.

Estou no curso no momento de criar o form, estou adicionando um input file, está tudo funcionando ok, porém preciso extrair o src da imagem e criar uma div correspondente, porém estou com dificuldades de como manipular isso.



buttonSave.addEventListener('click', function(e){

    e.preventDefault();

   const name = formAddStudent.name.value;
   const cpf = formAddStudent.cpf.value;
   const birtday = formAddStudent.birtday.value;
   const cellphone = formAddStudent.cellphone.value;
   const email = formAddStudent.email.value;
   const address = formAddStudent.address.value;
   const number = formAddStudent.number.value;
   const complement = formAddStudent.complement.value;
   const classStudent = formAddStudent.classStudent.value;

   const createDivContainerStudent = document.createElement('div');
   createDivContainerStudent.setAttribute('class', 'container-students');

   const createDivContainerStudentData = document.createElement('div');
   createDivContainerStudentData.setAttribute('class', 'container-students-data');

   const createTr = document.createElement('table');
   const nameTr = document.createElement('tr');
   const nameTd = document.createElement('td');
   const cpfTr = document.createElement('tr');
   const cpfTd = document.createElement('td');
   const birthdayTr = document.createElement('tr');
   const birthdayTd = document.createElement('td');
   const cellphoneTr = document.createElement('tr');
   const cellphoneTd = document.createElement('td');
   const emailTr = document.createElement('tr');
   const emailTd = document.createElement('td');
   const addressTr = document.createElement('tr');
   const addressTd = document.createElement('td');
   const numberTr = document.createElement('tr');
   const numberTd = document.createElement('td');
   const complementTr = document.createElement('tr');
   const complementTd = document.createElement('td');
   const classStudentTr = document.createElement('tr');
   const classStudentTd = document.createElement('td');

   nameTd.textContent = name;
   cpfTd.textContent = cpf;
   birthdayTd.textContent = birtday;
   cellphoneTd.textContent = cellphone;
   emailTd.textContent = email;
   addressTd.textContent = address;
   numberTd.textContent = number;
   complementTd.textContent = complement;
   classStudentTd.textContent = classStudent;

   createTr.appendChild(nameTr)
   nameTr.appendChild(nameTd)
   createTr.appendChild(cpfTr)
   cpfTr.appendChild(cpfTd)
   createTr.appendChild(birthdayTr)
   birthdayTr.appendChild(birthdayTd)
   createTr.appendChild(cellphoneTr)
   cellphoneTr.appendChild(cellphoneTd)
   createTr.appendChild(emailTr)
   emailTr.appendChild(emailTd)
   createTr.appendChild(addressTr)
   addressTr.appendChild(addressTd)
   createTr.appendChild(numberTr)
   numberTr.appendChild(numberTd)
   createTr.appendChild(complementTr)
   complementTr.appendChild(complementTd)
   createTr.appendChild(classStudentTr)
   classStudentTr.appendChild(classStudentTd)

   containerForm.appendChild(createDivContainerStudent)
   createDivContainerStudent.appendChild(createDivContainerStudentData)
   createDivContainerStudentData.appendChild(createTr)

// UPLOAD IMAGE e minha dúvida de como manipular o url e criar as div

inputImg.addEventListener('change', function(e) {
    const url = URL.createObjectURL(e.target.files[0]);

    const createDivContainerImgStudent = document.createElement('div');
    createDivContainerImgStudent.setAttribute('id', 'conteiner-img-students');

    const createDivImgProfile = document.createElement('img')
    img.src = url
    createDivImgProfile.setAttribute('id', 'img-students')

    createDivContainerStudentData.appendChild(createDivContainerImgStudent);
    createDivContainerImgStudent.appendChild(createDivImgProfile);


    })
})
1 resposta

E ai Silvio, tudo bem? Cara tinha a mesma dúvida a um tempo atrás, e consegui encontrar a solução no site stack Overflow, lá é um site de perguntas e respostas para programadores profissionais e entusiastas, recomendo deixar salvo em seus favoritos. Consegui o código base, e alterei colocando as minhas informações, vou deixar o link e o código que usei para tomar de exemplo (caso tenha outras imagens é só replicar o código trocando os elementos).

link Stack Overflow: https://pt.stackoverflow.com/questions/252279/mudar-atributo-src-de-uma-imagem-ao-fazer-upload-via-input-do-tipo-file

function previewFile() {
    const preview = document.querySelector('id ou classe da imagem');
    const file = document.querySelector('id do input').files[0];
    const reader = new FileReader();

    reader.addEventListener("load", () => {
      // convert image file to base64 string
      preview.src = reader.result;
    }, false);

    if (file) {
      reader.readAsDataURL(file);
    }
}

Obs: é interessante verificar se colocou a tag para chamar o JS corretamente:

<script src="./script.js"></script>

e outro ponto é se adicionou a função a ser chamado ao input no exemplo a seguir:

 <input id="exemplo" type="file" onchange="previewFile()" />

caso queira que o input não apareça, indico que seja colocado um atributo hidden no final da tag e adicione a função a uma label.

Espero ter ajudado, um abraço!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software