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

本文介绍如何使用Element UI的el-upload组件在不使用action属性的情况下,实现文件上传到后台接口的功能,同时限制一次只能上传一个文件,通过http-request钩子处理上传过程和错误提示。
摘要由CSDN通过智能技术生成

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

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

在这里插入图片描述

我们通过el-upload这个组件中的http-request钩子函数来实现
在这里插入图片描述

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大雄不是大熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值