2
respostas

Preview de imagem em um input

Boa noite, sei que não tem a ver com o curso, mas implementei uma rotina pra fazer upload de fotos para uma api, eu seleciono a foto usando o type="file", porem gostaria de ao selecionar a foto exibir ela no lugar da foto antiga, como se fosse um preview, mas não sei como passaria a imagem para o src do componente eu monto meu painel assim

<meu-painel :descricao="item.Descricao">
              <minha-imagem :url="item.Url" :descricao="item.Descricao"/>
              <input type="file" @change="ArquivoSelecionado" class="w3-button w3-indigo w3-round-xlarge w3-hover-indigo" style="max-width: 300px;"/>
              <button @click="onUpload" class="w3-button w3-green w3-round-xlarge w3-hover-green w3-margin" :id="item.Descricao">carregar para o site</button>
           </meu-painel>

aqui é onde eu seleciono o arquivo

ArquivoSelecionado(event){
      console.log(event);
      this.selectedFile = event.target.files[0];

           var input = event.target;
            // Ensure that you have a file before attempting to read it
            if (input.files && input.files[0]) {
                // create a new FileReader to read this image and convert to base64 format
                var reader = new FileReader();
                // Define a callback function to run, when FileReader finishes its job
                reader.onload = (e) => {
                    // Note: arrow function used here, so that "this.imageData" refers to the imageData of Vue component
                    //aqui é onde eu setaria a url da imagem que estou manipulando, mas como ela é um objeto do tipo categoria não sei como acessar essa propriedade dela
                    this.url = e.target.result;

                }
                // Start the reader job - read file as a data url (base64 format)
                reader.readAsDataURL(input.files[0]);
            }

    }

eu peguei parte do código daqui

https://jsfiddle.net/mani04/5zyozvx8/

aqui é onde eu monto as fotos

created(){
    let promise = this.$http.get('http://localhost:53592/home/fotos');
    promise
    .then(res => res.json())
    .then(categoria => this.categoria = categoria, err => console.log(err));
  },

e aqui é o código do componente foto

<template>
    <img :src="url" :alt="descricao" class="w3-margin-bottom">
</template>

<script>
export default {
    props:['url', 'descricao']
}
</script>

<style scoped>
img{
  width: 326px; 
  height: 400px;
  object-fit: cover; 
}
</style>
2 respostas

Consegui fazer percorrendo a lista de categoria, verificando se o valor da descrição é igual ao valor da id do próximo elemento se ele for igual eu troco a Url daquele elemento pela minha imagem, tem alguma forma melhor de fazer isso?

ArquivoSelecionado(event){
      this.selectedFile = event.target.files[0];
      this.categoria.forEach(element => {
        if(element.Descricao == event.target.nextSibling.id){

           var input = event.target;
            // Ensure that you have a file before attempting to read it
            if (input.files && input.files[0]) {
                // create a new FileReader to read this image and convert to base64 format
                var reader = new FileReader();
                // Define a callback function to run, when FileReader finishes its job
                reader.onload = (e) => {
                    // Note: arrow function used here, so that "this.imageData" refers to the imageData of Vue component
                    // Read image as base64 and set to imageData
                    element.Url = e.target.result;   
                }
                // Start the reader job - read file as a data url (base64 format)
                reader.readAsDataURL(input.files[0]);
            }
        }
      });
    }

Fala aí Rafael, tudo bem? Precisaria entender melhor o código e cenário, na maioria das vezes vai existir melhores maneiras de resolver um problema.

Para isso, seria importante entender a necessidade, o projeto, códigos JS e HTML, etc..

Por hora, acho que a solução está boa, não vejo como ruim, você conseguiu resolver o seu problema.

Espero ter ajudado.

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