如何使用Axios在Vue中上传图像

时间:2020-05-18 15:58:02

标签: node.js vue.js axios vuex vuetify.js

我找不到添加其中带有“图像”文件的对象的方法。

这就是我调用API的方式

export default {
  postCourse(course) {
    return apiClient.post('/course', course)
  }
}

vuex动作:-

createCourse({
      commit
    }, course) {
      CourseService.postCourse(course).then(() => {
        commit('ADD_COURSE', course)
      }).catch(err => console.log(err))
    }

在组件内部:-

methods: {
    createCourse() {
      let formData = new FormData()
      formData.append('image', this.media)
      this.$store
        .dispatch('createCourse', { course: this.course, formData })
        .then(() => {})
        .catch(() => console.log('err'))
    },
    handleFileUpload(e) {
      this.media = e
    }
  }

并收到该错误 POST http://127.0.0.1:3333/api/v1/course 422(不可处理的实体)

1 个答案:

答案 0 :(得分:0)

您不是在发帖请求中发送formData

.dispatch('createCourse', { course: this.course, formData })

// Only the course object is passed the formData is not used ?? why ?
CourseService.postCourse(course).then(() => {
    commit('ADD_COURSE', course)
}).catch(err => console.log(err))

postCourse(course) {
    // Same case here only the Course is being posted you haven't used the formData ?
    return apiClient.post('/course', course)
}

实际上,您是以json形式发布课程数据,而仅以FormData形式发布图像,但这实际上是无法完成的。您只能一次使用JSONFormData。因此,首先需要使用courseformData对象的所有条目添加到该.append对象中并通过formData而不是course

就是这样

.dispatch('createCourse', { course: formData })