Vue Axios-使用bootstrapVue和vuex,仍然无法上传文件和文本吗?

问题描述 投票:0回答:1

我有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);
      });
   }
}
vue.js axios vuex bootstrap-vue
1个回答
0
投票

当您要上传图像时,必须设置内容类型并创建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)
© www.soinside.com 2019 - 2024. All rights reserved.