0

I have vue SPA and I trying to upload some images and text. I try using postman to test my server code and it's work, but my client-side still error. I think I'm still mistaken for handle req.file.

  1. addImage.vue
<template>
<div>
  <b-form-group label-cols-sm="3" description="image title" label="Title">
     <b-form-input v-model="newImage.title"></b-form-input>
  </b-form-group>

  <b-form-group label="my Image" label-for="file" label-cols-sm="2">
    <b-form-file id="file" v-model="newImage.image"></b-form-file>
  </b-form-group>

  <b-button variant="primary" class="pl-5 pr-5" @click.prevent="addImage">Save</b-button>
</div>
</template>

<script>
export default {
  data() {
    return {
      newImage: {
        title: '',
        image: null,
      },
    };
  },
  methods: {
    addImage() {
      this.$store.dispatch('addProduct', this.newProduct);
    }
  },
};

  1. store.js
actions: {
  addImage(context, newImage) {
    const config = {
      headers: {
        token: localStorage.getItem('token'),
      },
    };

    Axios
      .post(`${baseUrl}/product`, newImage, config)
      .then(({ newImage }) => {
        context.commit('ADD_IMAGE', newImage);
      })
      .catch((err) => {
        console.log(err.message);
      });
   }
}
5
  • Please show your error code. Commented Oct 1, 2019 at 14:52
  • is this the actual code? because I see many differente variables names.... Commented Oct 1, 2019 at 14:52
  • no, some I change for a simple Commented Oct 1, 2019 at 14:56
  • I try to console.log(newImage) upper Axios and I get the data, but console.log(newImage) below Axios .then, the result is undefined Commented Oct 1, 2019 at 15:20
  • hi, i'm not sure, but, could you try to remove the curly brackets on .then((newImage)=> {}) have you a demo on codepen or other service like this? Commented Oct 4, 2019 at 14:12

1 Answer 1

1

When you want to upload an image you have to set the content type and create FormData, like this:

    let data = new FormData();

    for (var i = 0; i < files.length; i++) {
        let file = files.item(i);
        data.append('images[' + i + ']', file, file.name);
    }

    const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }

    return axios.post('/api/images', data, config)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.