【问题标题】:Vue Axios - with bootstrapVue and vuex, still problem to upload file and text?Vue Axios - 使用 bootstrapVue 和 vuex,上传文件和文本仍有问题?
【发布时间】:2020-01-30 21:32:34
【问题描述】:

我有 vue SPA,我正在尝试上传一些图片和文本。我尝试使用邮递员来测试我的服务器代码并且它可以工作,但我的客户端仍然错误。 我想我仍然误认为是句柄 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);
      });
   }
}

【问题讨论】:

  • 请显示您的错误代码。
  • 这是实际代码吗?因为我看到许多不同的变量名称......
  • 不,我换了一些简单的
  • 我尝试console.log(newImage)Axios得到数据,但console.log(newImage)Axios .then,结果未定义
  • 嗨,我不确定,但是,您能尝试删除 .then((newImage)=&gt; {}) 上的大括号吗?您有关于 codepen 或其他类似服务的演示吗?

标签: vue.js axios vuex bootstrap-vue


【解决方案1】:

当您要上传图片时,您必须设置内容类型并创建 FormData,如下所示:

    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)

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 2019-07-26
    • 2019-06-28
    • 2021-01-10
    • 2021-02-26
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多