入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Element UI - http-request 覆盖默认的上传行为,自定义上传的实现

创建时间:2018-02-02 投稿人: 浏览次数:1679

结合文章 - 阿里OSS Java-SDK带进度条上传,配合前端element-ui upload组件使用示例

表单中的 ui

<el-form-item label="课程文件" :label-width="formLabelWidth">
    <el-upload
            :show-file-list="false"
            :file-list="playUrls"
            :http-request="uploadSectionFile"> <!--此处使用自定义上传实现http-request-->
        <el-button size="small" type="primary">点击上传</el-button>
        <el-tag v-show="showSectionFileName" type="gray">{{sectionFileName}}</el-tag>
        <div slot="tip" class="el-upload__tip">请等待进度条100%之后再提交表单</div>
    </el-upload>
    <el-progress v-show="showProgress" :text-inside="true" :stroke-width="18"
                 :percentage="uploadPercent"></el-progress>
</el-form-item>

http-request指向的函数会有一个element 的默认回调参数 定义为param.里面包含很多东西,可以自己debug查看
param.file就是要上传的文件

uploadSectionFile: function (param) { //自定义文件上传
    var fileObj = param.file;
    // 接收上传文件的后台地址
    var FileController = "/file/item/upload";
    // FormData 对象
    var form = new FormData();
    // 文件对象
    form.append("file", fileObj);
    // 其他参数
    form.append("xxx", xxx);
    // XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();
    xhr.open("post", FileController, true);
    xhr.upload.addEventListener("progress", vm.progressFunction, false); //监听上传进度
    xhr.onload = function () {
        vm.Form.playUrl = xhr.response; //接收上传到阿里云的文件地址
        vm.$message({
            message: "恭喜你,上传成功!",
            type: "success"
        });
    };
    xhr.send(form);
},

监听上传进度中指定的函数,此函数在上传过程中会一直执行,所以通过 i来控制只执行一次

progressFunction: function () {
  if (vm.i == 0) { //控制上传中状态只执行一次上传
        vm.showStatus();
        vm.showProgress = true;
        vm.i = 1;
    }
},

定时查询上传进度 uploadPercent是上传进度

showStatus: function () { 
    var intervalId = setInterval(function () {
        $.get("/file/item/percent", {}, function (data) {
            var percent = data;
            if (percent >= 100) {
                clearInterval(intervalId);
                percent = 100;//不能大于100
                vm.uploadPercent = percent;
                vm.resetPercent(); //在文章开头的上篇文章中有此函数,用于重置后台的上传进度
            }
            vm.uploadPercent = percent;
        }, "json");
    }, 1000);
},
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。