upload-xlsx.vue 2.49 KB
<template>
    <div @click="handleClick" style="display: inline-block;">
        <input ref="input" type="file" accept=".xlsx" @change="handleChange">
        <slot></slot>
    </div>
</template>

<script>
    import request from 'axios';

    export default {
        name: 'XlsxUpload',
        props: {
            action: {
                type: String,
                default() {
                    return '/upload/xlsx';
                }
            },
            onSuccess: {
                type: Function,
                default() {
                    return {};
                }
            },
            onError: {
                type: Function,
                default() {
                    return {};
                }
            },
            onProgress: {
                type: Function,
                default() {
                    return {};
                }
            },
            onChange: {
                type: Function,
                default() {
                    return {};
                }
            }
        },
        data() {
            return {
                files: null
            };
        },
        methods: {
            handleClick() {
                this.$refs.input.click();
            },
            handleChange(e) {
                this.files = e.target.files;
                this.onChange(this.files);
            },
            upload() {
                let files = this.files;
                let postFiles = Array.prototype.slice.call(files);

                postFiles = postFiles.slice(0, 1);

                if (postFiles.length === 0) {
                    return;
                }

                return this.post(postFiles[0]);
            },
            clear() {
                this.files = null;
            },
            post(file) {
                let _this = this;
                let config = {
                    onUploadProgress(processEvent) {
                        _this.onProgress(processEvent);
                    }
                };
                let data = new FormData();

                data.append('file', file);

                return request.post(this.action, data, config)
                    .then((result) => {
                        _this.onSuccess(result.data);
                    })
                    .catch((err) => {
                        _this.onError(err);
                    });
            }
        }
    };
</script>

<style lang="scss" scoped>
    input[type="file"]{
        display: none;
    }
</style>