Search code examples
vue.jsrails-api

Carrierwave: upload an image from vue front to rails api


I am not sure how to make the axios post for the image.

This is what my json object looks like.

{
 "id":20,
 "title":"pineapple",
 "text":"pineapple",
 "date":null,
 "created_at":"2019-03-23T01:42:48.142Z",
 "updated_at":"2019-03-23T01:42:48.142Z",
 "image":{
          "url":null
         }
 }

This is my image input from the Vue form.

<input  type="file" 
        id="file" 
        ref="myFiles" 
        class="custom-file-input" 
        @change="takeFile" 
        multiple>

Here is me trying to make sense of it.

export default {
    data() {
      return {
        blog: {
          title: '',
          content: '',
          link: ''
        }
      }
    },
    methods: {
      submitArticle(blog) {
        console.log('blog.link', blog.link)
        axios.post('http://localhost:3000/articles', {
          title: blog.title,
          text: blog.content,
          image: {
            url: blog.link 
          }
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      },
      takeFile(event) {
        console.log(this.$refs.myFiles.files);
        this.blog.link = this.$refs.myFiles.files
      }
    }
  }

Here is a link to the file in my repo.


Solution

  • First this.$refs.myFiles.files returns an array of files. Change your method like this to set the file to blog.link:

    takeFile(event) {
      this.blog.link = this.$refs.myFiles.files[0]
    }
    

    Now to send file in your post request, you should use FormData:

    submitArticle(blog) {
      let formData = new FormData()
      formData.append("article[title]", blog.title)
      formData.append("article[text]", blog.content)
      formData.append("article[image]", blog.link)
      axios.post('http://localhost:3000/articles', formData, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function (response) {
        console.log(response)
      }).catch(function (error) {
        console.log(error)
      })
    },