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

357
Visualizações
I can't upload image files from .vue to my database

I'm using Vue with Laravel and I tried to do a simple crud which is working good regarding things like title or description of an article (text-fields) but when I try to send an image file, it doesn't work. I have tried formData but to no avail.

This is my form in template, title goes in the database with no problem, if I console log selectedFile then it shows the file selected correctly but the addArticle method not attaching the images

<form @submit.prevent="addArticle" class="container">
      <label>Title</label>
      <input type="text" v-model="article.title" />
      <label>Image</label>
      <input type="file"  v-on:change="selectedFile"  />
      <button type="submit">Create</button>
</form>

This is my script

<script>
export default { 
  data() {
    return {
      fileSelected: null,       
      article: {},
    };
  },

  methods: {
    addArticle() {
       var formData =new FormData();
       formData.append(this.article.image, this.fileSelected);
        
      axios
        .post("http://localhost:8000/api/articles", this.article) 
        .then((response) => this.$router.push({ name: "ArticlesList" }))
        .catch((err) => console.log(err))
        .finally(() => (this.loading = false));
      }
    ,

    selectedFile(event) {
      this.fileSelected = event.target.files[0];
    },
  },
};
</script>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

this is my code

<input type="file" @change="onFileChange">


  onFileChange(e) {
    this.sendphoto = e.target.files[0];

  },

  editUser() {
    var self = this;
    let formData = new FormData();
   
      formData.append("image" , self.sendphoto )
  
    let config = {
      header : {
        'Content-Type' : 'multipart/form-data'
      }
    }
    axios.post('/edit-user' , formData , config)
            .then(function (response) {

            })
            .catch(function (error) {
              console.log(error);
            })
  },
about 4 years ago · Juan Pablo Isaza Relatório

0

You are creating a FormData object but you are not sending it within your Axios request. In order to send the file and form data, you have to append everything to FormData object.

<script>
export default { 
  data() {
    return {
      fileSelected: null,       
      article: {},
    };
  },

  methods: {
    addArticle() {
      var formData =new FormData();
      formData.append('image', this.fileSelected);
      formData.append('title', this.article.title);
        
      axios
        .post("http://localhost:8000/api/articles", formData) 
        .then((response) => this.$router.push({ name: "ArticlesList" }))
        .catch((err) => console.log(err))
        .finally(() => (this.loading = false));
      }
    ,

    selectedFile(event) {
      this.fileSelected = event.target.files[0];
    },
  },
};
</script>
about 4 years ago · Juan Pablo Isaza Relatório

0

this worked in sending image files as string on database, hopefully it helps other people that are having similar problems

setup() {
        const base64 = ref()
        const changeFile= async(event) => {
            const file = event.target.files[0]; 
            base64.value = await convertBase64(file);          
        }    
 
        const convertBase64 = (file) => {
            return new Promise ((resolve, reject) => {
                const fileReader = new FileReader();
                fileReader.readAsDataURL(file);

                fileReader.onload = () => {
                    resolve(fileReader.result)
                }

                fileReader.onerror = (error) => {
                    reject(error)
                }
            })
        } 
  
        const form = reactive({
            title: " ",
            body: " ",
            image:  base64,
        })
     
        const submitForm = () => {            
            axios.post("http://localhost:8000/api/articles", form)
        }
        return { changeFile, submitForm, form}
    },

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