elementUI el-upload自定义上传文件,不用action属性

elementUI el-upload自定义上传文件,不用action属性

需求描述:如图所示,点击选择文件后,只是选择文件,在点击上传的时候调后台接口而不是上传到fastDFS服务器,并且要限制该文件只能上传一个。

elementUI el-upload自定义上传文件,不用action属性_第1张图片

我们通过el-upload这个组件中的http-request钩子函数来实现
elementUI el-upload自定义上传文件,不用action属性_第2张图片

handleUpload(params) 中的这个参数建议直接打印出来看一下,里面有file,当前文件,有onSuccess,onError,onProgress三个方法。一个成功回调,一个失败回调,还有一个是显示进度条的。

<template>
    <div class="page" v-loading="fullscreenLoading">
        <div class="pageInner">
            <span style="font-size: 22px;font-weight: 700;">航线信息维护</span>
            <hr ssize="0.5" />
            <div style="padding-top: 20px; font-size: 14px;">
                注:请根据
                 <a :href="exportTemplateUrl" download="航线信息维护模板文件.xls">模板文件</a>
                格式进行数据填写,并上传文件
            </div>

            <el-upload
                    class="upload-demo"
                    ref="upload"
                    id="1"
                    action=""
                    :limit="1"
                    accept=".xls, .xlsx"
                    :on-change="handleChange"
                    :on-remove="handleRemove"
                    :http-request="handleUpload"
                    :on-exceed="handleExceed"
                    :file-list="fileList"
                    :auto-upload="false">

                <el-button style="margin: 20px 0 0 0;" slot="trigger"  type="primary">选取文件</el-button>
                <el-button style="margin-left: 20px; "  type="success" @click="submitUpload">上传</el-button>
            </el-upload>
        </div>
    </div>
</template>

<script>
    import Bus from "@/assets/js/bus";
    import config from "@/assets/js/config";
    import utils from "../../../../assets/js/utils";
    import api from "@/assets/js/api/basicConfiguration/routeMaintenance/apiMethod";
    import apiUrl from "@/assets/js/api/basicConfiguration/routeMaintenance/apiUrl";
    import axios from 'axios'
    import Vue from "vue";

    export default {
        name: "RouteMaintenance",
        components: {
        },
        data() {
            return {
                fileList: [],
                uploadFlag: false,
                fullscreenLoading: false,
            }
        },
        created() {
            let self = this
        },
        methods: {
            submitUpload() {
                if(! this.uploadFlag){
                    this.$message.error("请先选择文件!");
                } else{
                    this.$refs.upload.submit();
                }
            },
            handleRemove(file, fileList) {
                this.uploadFlag = false
            },
            handleChange(file, fileLists){
                const isLt5M = file.size / 1024 / 1024 < 20;  //不能超过20M
                // const isPNG = file.type === 'image/png';
                // const isJPG = file.type === 'image/jpeg';
                // const isPDF = file.type === 'application/pdf';
                // const isDOCX = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                // const isDOC = file.type === 'application/msword';
                const isXLSX = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                const isXLS = file.raw.type === 'application/vnd.ms-excel';
                const fileFormat = (isXLSX || isXLS);
                if (!isLt5M) {
                    this.$message.error('上传文件大小不能超过 20MB!');
                    this.fileList = []
                }
                if (!fileFormat) {
                    this.$message.error('上传格式不支持!格式仅支持:XLS、XLSX');
                    this.fileList = []
                }
                this.uploadFlag = true
                return isLt5M && fileFormat;
        	},

            handleUpload(params) {
                let self = this
                let fd = new FormData();
                let config = {
                    headers: {},
                    timeout: 300000
                }
                let headers = config.headers
                headers['Access_Token'] = utils.getCookie("token2")
                fd.append('file', params.file);

                self.fullscreenLoading = true
                axios.post(apiUrl.importService, fd, config).then(res => {
                    // console.log(res)
                    self.fullscreenLoading = false
                    if(res.data.code == '0'){
                        this.$message({
                            message: '导入成功!',
                            type: 'success'
                        });
                    }else {
                        self.$notify.error({
                            title: "提示",
                            message: res.data.message
                        })
                    }
                }).catch(function(e) {
                    self.fullscreenLoading = false
                    if (e.response && e.response.status == 500) {
                        Vue.prototype.$message.error("连接服务器失败,请稍后重试!");
                    } else if (e.response && e.response.status == 99) {
                        Vue.prototype.$message.error("系统异常,请稍后重试!");
                    } else {
                        Vue.prototype.$message.error("请求接口失败,请检查网络!");
                    }
                });

            },
            handleExceed(files, fileList) {
                // this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
                this.$message.warning(`当前限制选择 1 个文件!`);
            },

            handleClose: function (done) {
                let self = this
                Bus.$emit("delCurrentTab", "businessQuery/CntrDetail");
            },
        }
    }
</script>

<style lang="scss" scoped>
    .upload-demo ::v-deep .el-upload-list .el-upload-list__item{
        /*margin-top: 4%;*/
        height:20px;
        width:300px;
        line-height: 20px;
    }

    .page{
        background: white;
        width: 98%;
        margin: 1% 0 0 2%;
        height: calc(100vh - 105px);
        overflow: auto;

        .pageInner{
            margin: 3% 3% 3% 3%;
        }
    }
</style>

你可能感兴趣的:(vue,elementui,javascript,vue.js)