Search code examples
vue.jsvuexquasar

How to upload a photo in my Form and into my Vuex store?


I'm practicing building a Hybrid Mobile app with Quasar, Vue and Vuex. I've successfully added my form input fields to my Vuex store but I don't know how to upload a file, in this case a photo, within my Form.

Here is my q-file input from my form, with the data.

<q-file
 v-model="mealToSubmit.photo"
 label="Upload File"
 outlined
>

Data:

data () {
    return {
      mealToSubmit: {
        name: '',
        description: '',
        photo: null,
        grams: '',
        calories: '',
        visible: false
      }
    }
  }

After I fill in the Form and click Save, all of the data appears on the page except for the photo I selected. In the console I get a 404 error: 404  http://localhost:8080/img/null 404 (Not Found)

I can see the problem here is that it's displaying null, instead of the name of the photo I upload, which is why I'm getting a 404 error.

Here are two screenshots, one of me filling in the Form and second is the data being displayed properly except for the photo, with the error message in the console. enter image description here enter image description here NOTE:

Just to add to this, I've uploaded files before using Vue js and Bootstrap-Vue. I add an @change event on the File input with a v-model like this:

<b-form-group label="Upload Profile Photo (optional)" label-for="photo_id">
    <b-form-file
        v-model="profileData.photo_id"
        id="photo_id"
        placeholder="Choose a file..."
        @change="attachImage"
        accept=".jpg, .jpeg, .png"
    ></b-form-file>
</b-form-group>

Than in the Methods{}:

methods: {
  attachImage(evt) {
    const file = evt.target.files[0];
    let reader = new FileReader();
    reader.addEventListener('load', function() {
    }.bind(this), false);
    reader.readAsDataURL(file);
  },
}

And then I bind the data using FormData(); and send it to the backend. This approach isn't working with the Quasar file upload input and the code that I have above.


Solution

  • I got it now:

    <q-file
      @input="getFile"
      label="Upload file"
    />
    methods: {
      getFile(file) {
        // file is in the file variable
        this.mealToSubmit.photo = file
      }
    }