使用laravel,vue和axios上传多张图片

时间:2019-12-28 22:57:24

标签: laravel vue.js axios interceptor

点击上传方法时文件没有上传。

我认为此问题是由于 axios拦截器造成的,因为当我创建新的axios实例并将标头设置为

headers: {'Authorization': 'Bearer ' + this.user.api_token }

它就像一种魅力。

有什么方法可以使它工作而无需创建新的axios实例?因为我无法访问ImageUploader组件中的用户对象?

ImageUploader.vue

<template>
   <div>
      <label for="file">Select a file</label>
      <input type="file" id="file" @change="onInputChange" multiple>
   </div>

   <div class="upload-control" v-show="images.length">
      <label for="file">Select a file</label>
      <button @click="upload">Upload</button>
   </div>
<template/>


<script>
export default {

    data: () => ({
        files: [],
        images: []
    }),


    methods: {
        onInputChange(e) {
            const files = e.target.files;
            Array.from(files).forEach(file => this.addImage(file));
        },

        addImage(file) {
            if (!file.type.match('image.*')) {
                this.$toastr.e(`${file.name} is not an image`);
                return;
            }
            this.files.push(file);
            const img = new Image(),
                reader = new FileReader();
            reader.onload = (e) => this.images.push(e.target.result);
            reader.readAsDataURL(file);
        },

        upload() {
            const formData = new FormData();

            this.files.forEach(file => {
                formData.append('images[]', file, file.name);
            });


            axios.post('/api/products', formData)
                .then(response => {
                    this.images = [];
                    this.files = [];
                })
        },


    },
}

App.vue

<script>
    import SearchBar from "./SearchBar";
    export default {
        name: "App",

        props: [
            'user'
        ],

        components: {
            SearchBar
        },

        created() {
            this.title = this.$route.meta.title;
            window.axios.interceptors.request.use(config => {
                if (config.method === "get") {
                    config.url = config.url + "?api_token=" + this.user.api_token;
                } else {
                    config.data = {
                        ...config.data,
                        api_token: this.user.api_token
                    };
                }
                return config;
            });
        },
    }
</script>

0 个答案:

没有答案