Home > database >  I can't upload image files from .vue to my database
I can't upload image files from .vue to my database

Time:02-28

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" >
      <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>

CodePudding user response:

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);
            })
  },

CodePudding user response:

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>
  • Related