element-ui upload上传技巧

本文章应用场景是:

前端使用的是vue.js和element-ui。

上传是包含在一个表单里面,使用element-ui的upload上传组件,想实现的是在我点击上传选择文件后不让它自动提交,而是在我点击确定后,经过一系列的验证再提交。而且element-ui的upload组件上传的路径跟表单保存的路径是不一样的。具体看代码。 

<!-- 新增弹窗-->
        <el-dialog title="上传文件" :visible.sync="dialogFormVisible" width="40%">
            <el-form :model="form" status-icon :rules="rules" ref="form">
                <el-row type="flex" justify="center">
                    <el-col :span="22">
                        <el-form-item label="上报机构:" :label-width="formLabelWidth" prop="organization">
                            <el-input v-model="form.organization" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="22">
                        <el-form-item label="上传文件:" :label-width="formLabelWidth">
                            <el-upload
                                    class="upload-demo"
                                    ref="upload"
                                    :with-credentials="true"
                                    :limit="5"
                                    :file-list="fileList"
                                    :data="myData"
                                    :action="uploadUrl()"
                                    :headers="myHeader"
                                    :on-change="addFile"
                                    :on-remove="removeFile"
                                    :auto-upload="false"
                            >
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="insert('form')">确 定</el-button>
            </div>
        </el-dialog>

 :file-list="fileList",这个fileList是自己定义的一个文件列表,显示的文件就是这个里边的文件。不要跟下面函数里面的fileList搞混了,函数里面的是element-ui自己封装的一个变量。具体看它的官网。
:action="uploadUrl()"是动态设置的文件上传路径。

uploadUrl:function(){
    return "http://127.0.0.1:8081/uploadFile";
},
:data="myData"是设置上传携带的其他的数据。
myData(){
    return {
        "businessId":this.form.fileId,
        "businessType":"sys_file"
    }
}
:headers="myHeader"是设置的请求头
myHeader(){
    return {
        "authToken":window.sessionStorage.getItem('authToken')
    }
},

这里值得一提的是,在使用element-ui和vue.js的时候,设置:data和:headers要在vue.js的计算属性里面添加

computed: {
    myHeader(){
        return {
            "authToken":window.sessionStorage.getItem('authToken')
        }
    },
    myData(){
        return {
            "businessId":this.form.fileId,
            "businessType":"sys_file"
        }
    }
},

这样就能加上,如果有其他的方法也可以试一试。

判断文件大小:

addFile(file,fileList){
    this.fileList = fileList;
    //限制上传文件为5M
    var sizeIsSatisfy = file.size < 5*1024*1024 ? true:false;
    if(sizeIsSatisfy){
        return true;
    }else{
        this.fileSizeIsSatisfy = false;
        return false;
    }
}, 

这里用的是::on_change事件,它会在文件添加的时候去条用addFile方法,就做验证,fileSizeIsSatisfy是我定义的一个变量,当我上传的文件中存在大于5M的文件时,fileSizeIsSatisfy = false,在点击提交时就会提示存在大于5M的文件,不能提交。暂时没找到添加一个文件的时候,就让它从文件列表中移除这个fileList是它封装的一个文件列表,暂时没找到,只能先这样折中的办法。

 

下面就是我点击确认的时候执行的insert方法。

insert(formName) {
    this.$refs[formName].validate((valid) => {
        if (valid) {
            if(this.fileList.length <= 0){
                this.$message.error("请至少上传一个文件!");
                return;
            }
            if(!this.fileSizeIsSatisfy){
                this.$message.error("上传失败!存在文件大小超过5M!");
                return;
            }
            //手动上传文件,在点击确认的时候 校验通过才会去请求上传文件的url
            this.$refs.upload.submit();
            this.postRequest("/api/rcs/sysFile",this.form).then((res)=>{
                if(res.data.status == 200){
                    this.form = {};
                    this.fileList = [];
                    this.dialogFormVisible = false;
                    this.$message.success('新增成功!');
                    this.getUploadList(1);
                }else{
                    this.$message.error(res.data.msg);
                }
            })
                .catch((error)=>{
                    this.$message.error(error)
                })
        } else {
            this.$message.error('error submit!!');
            return false;
        }
    });
},

在执行到this.$refs.upload.submit();的时候才会去请求文件上传的地址进行文件上传。

Element-UIUpload组件主要用于处理文件上传,包括图片、文本等常见格式。如果你想要手动上传Excel文件,你可以按照以下步骤操作: 1. 首先,你需要安装Element-UI以及相关的文件上传插件,如`axios`用于发送HTTP请求,因为`element-upload`本身并不直接支持上传Excel文件。 ```bash npm install element-ui axios ``` 2.Vue项目中引入Element-UIUpload组件: ```html <template> <el-upload :action="uploadUrl" :on-change="handleChange" :file-list="fileList" accept=".xls,.xlsx" <!-- 表示接受.xls和.xlsx类型的文件 --> > <i class="el-icon-upload"></i> 点击<em>上传</em> </el-upload> </template> <script> import axios from 'axios'; export default { components: { ElUpload }, data() { return { fileList: [], uploadUrl: 'your-api-url-to-upload', // 替换为你实际的上传接口地址 }; }, methods: { handleChange(file) { if (!file.type.includes('application/vnd.ms-excel')) { this.$message.error('只支持Excel文件'); return; } const reader = new FileReader(); reader.onload = (e) => { axios.post(this.uploadUrl, e.target.result, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log('上传成功:', response); // 更新文件列表或处理服务器响应 }) .catch(error => { console.error('上传失败:', error); }); }; reader.readAsArrayBuffer(file); } } }; </script> ``` 在这个例子中,当用户选择一个Excel文件后,`handleChange`方法会读取文件内容,并使用axios发送POST请求到指定的API。注意,由于浏览器安全限制,`FileReader` API只能读取二进制数据,所以我们需要设置`Content-Type`为`multipart/form-data`以便于服务器识别。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值