zoukankan      html  css  js  c++  java
  • element 上传-Upload

    常规用法

    <template>
      <g-dialog 
          @confirm="confirm" //点击确认
          :dialogVisible.sync="dialogVisible"
          width="460"
          :center="true"
          title="导入扫描件"
          :isUpload="true"> //是否上传,上传的话手动关闭dialog,否则上传清空数组会失败  
        <el-upload
            action="api.php/mistakeTitle/addTitleAnnex"
            ref="upload"
            class="upload-demo"
        	:on-change="onChange" //文件发生改变
            :on-progress="onProgress"  //上传时
            :on-success="onSuccess" //上传成功
            :on-error="onError" //上传失败
            :on-remove="onRemove" //文件移除
            drag //拖动
            accept=".zip" //文件格式
            :file-list="fileList" //文件数组
            :limit="1" //文件个数
            :auto-upload="false" //自动上传
            :headers="httpHeader" //附带请求头       
            :data="{title_id,student_id}" //附带参数
                   >
      </g-dialog>        
    </template>
        
    <script>
    import { Loading } from "element-ui";
    export default {
      data() {
        return {
          httpHeader: {
            token: localStorage.getItem("token"),
            uid: localStorage.getItem("uid")
          },
          dialogVisible:false,
          fileList: [], //上传文件
          Loading: "" //Loding实例
        };
      },
      methods: {
        //这里限制上传格式或者大小  
        uploadChange(file, fileList) {
          this.fileList = fileList;
          var type = file.name.substring(file.name.lastIndexOf(".") + 1);
          let flag = type === 'image/jpeg'||'image/gif'||'image/png';
          if (!flag) {
            this.fileList = [];
            this.$message.warning("请上传zip格式文件");
          }
          return flag;
        },
        //开启弹框  
        onProgress() {
          this.Loading = Loading.service({
            text: "正在上传中",
            background: "rgba(255, 255, 255, 0.5)",
            target: "body"
          });
        },
        //上传成功,这里才手动关闭dialog  
        uploadSuccess() {
          this.Loading.close();
          this.fileList = [];//清空数组
          this.$refs.upload.clearFiles();//清空已上传的文件
          this.$message.success("操作成功");
          this.dialogVisible = false;
          //重新发送获取表格
          this.onSubmit();
        },
        uploadError() {
          this.Loading.close();
          this.$message.success("操作成功");
          this.dialogVisible = false;
        },
        uploadRemove(file, fileList) {
          this.fileList = fileList;
        },
        //当弹窗点击确定,手动调用upload上传功能  
        confirm() {
          this.$refs.upload.submit();
        }
      }
    };
    </script>    
    

    二次封装upload组件

    实现功能

    1. 自定义手动上传服务器
    2. 可以根据文件数量隐藏图片上传按钮
    3. 可根据type属性切换不同上传样式
    4. 父组件通过手动调用函数this.$refs.upload.manualUpload()完成上传
    5. 父组件通过success事件,接受上传成功后返回的参数
    6. 可以使用插槽自定义样式
    <template>
      <div>
        <el-upload
          ref="upload"
          :class="{'hide':hideUpload}"
          :limit="limit"
          :action="url"
          :auto-upload="auto"
          :http-request="uploadFile"
          :list-type="type"
          :file-list="fileList"
          :on-change="onChange"
          :on-remove="onRemove"
          :on-progress="onProgress"
          :on-success="onSuccess"
          :on-error="onError"
          v-bind="$attrs"
          v-on="$listeners"
          :drag="type==='drag'"
        >
        <slot>
          <template v-if="type==='picture-card'">
            <i class="el-icon-plus"></i>
          </template>
          <template v-if="type==='button'||type==='picture'">
            <el-button size="small" type="primary">点击上传</el-button>
          </template>
          <template v-if="type==='drag'">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处,或
              <em>点击上传</em>
            </div>
          </template>
         </slot>    
          <div v-if="tip" slot="tip" class="el-upload__tip">{{tip}}</div>
        </el-upload>
      </div>
    </template>
    
    <script>
    export default {
      name: "g-upload",
      inheritAttrs: false,
      props: {
        url: {
          type: String,
          default: "https://jsonplaceholder.typicode.com/posts/"
        },
        auto: {
          type: Boolean,
          default: false
        },
        //text/picture/picture-card/button/drag
        type: {
          type: String,
          default: "picture-card"
        },
        //数量    
        limit: {
          type: Number,
          default: 1
        },
        //提示    
        tip: {
          type: String
        }
      },
      data() {
        return {
          hideUpload: false, //控制显示隐藏
          fileList: [],
          formData: ""
        };
      },
      methods: {
        onChange(file, fileList) {
          this.hideUpload = fileList.length >= this.limit;
        },
        onRemove(file, fileList) {
          this.hideUpload = fileList.length >= this.limit;
        },
        onProgress() {},
        // 自定义上传函数
        uploadFile(file) {
          this.formData.append("file[]", file.file);
        },
        //手动上传按钮触发函数 this.$refs.upload.manualUpload()
        manualUpload(data) {
          this.formData = new FormData();
          this.$refs.upload.submit(); // 触发上传
          Object.keys(data).forEach(key => {
            this.formData.append(key, data[key]);
          });
    
          let res = this.$axios.post(this.url, this.formData, {
            headers: { "Content-Type": "multipart/form-data" }
          });
    
          this.hideUpload = false;
          this.$refs.upload.clearFiles();
          res
            .then(res => {
              this.$emit("success", res);//父组件可在该事件中关闭弹框等操作
              this.$message.success("上传成功");
            })
            .catch(err => {
              console.log("err =", err);
            });
        },
        //在自定义上传事件的.then和.catch中  无需再使用下面函数    
        onSuccess() {},
    
        onError() {}
      }
    };
    </script>
    
    <style lang="scss" scoped>    
    /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
       auto;
      height: auto;
      max- 100%;
      max-height: 100%;
    }
    /deep/ .hide .el-upload--picture-card {
      display: none;
    }
    </style>
    

    使用实例

    <template>
      <div>
        <div @click="manualUpload">手动上传</div>
        <g-upload
          :limit="3"
          tip="12122"
          @success="success"
          url="mistakeTitle/uploadTopic"
          ref="upload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </g-upload>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          flag: false,
          //附带的参数  
          param: {
            num_id: 1667
          }
        };
      },
      created() {},
      methods: {
        manualUpload() {
          this.$refs.upload.manualUpload(this.param);
        },
        success(res) {
          console.log("res =", res);
        }
      }
    };
    </script>
    
    <style lang="scss" scoped>
    </style>
    
  • 相关阅读:
    Java学习开篇
    《我的姐姐》
    世上本无事,庸人自扰之
    这48小时
    补觉
    淡定
    es java api 设置index mapping 报错 mapping source must be pairs of fieldnames and properties definition.
    java mongodb groupby分组查询
    linux 常用命令
    mongodb too many users are authenticated
  • 原文地址:https://www.cnblogs.com/cjh1996/p/12842403.html
Copyright © 2011-2022 走看看