使用el-upload和原生input实现单文件、多文件上传

一、实现文件上传

1、单文件上传

每次只能上传一个文件,再次上传文件时

     

<div style="padding-left: 40px;">
  <el-upload class="upload-demo" drag accept=".pdf" action="" :on-change="handleChange" :http-request="handleUploadFile" :file-list="uploadfileList">
     <i class="el-icon-upload"></i>
     <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传PDF文件,且不超过100M</div>
  </el-upload>
</div>
    handleChange(file, fileList) {
      //清空上传列表中的数据 保证列表中只有一个文件
      this.uploadfileList = []
      const isLt5M = (file.size / 1024 / 1024) < 100;
      if (!isLt5M) {
        this.$message.error(file.name + "  文件错误!!!" + "  最大只能上传100M的文件");
        return false;
      }
      //获取文件后缀
      var extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (extName === '.pdf') {
        this.uploadfileList.push(file.raw)
      } else {
        this.$message.error("只能上传PDF文件");
        return false;
      }
    },
    handleUploadFile() {
      var formData = new FormData();
      //this.uploadfileList[0] 单文件上传,数组中只会有一个
      //uploadHistoryMind 接口传的参数是file
      formData.append("file", this.uploadfileList[0]);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }
      uploadHistoryMind(formData, config).then((res) => {
        if (res.code == 20000) {
          //存储上传成功的文件信息数据
          this.currentFileInfo = res.data;
        }
      }).catch((err) => {
         this.$message.error(err.msg)
      });
    },

2、多文件上传

取消自动上传,上传多个文件后点击按钮提交服务器

before-upload只在auto-upload为true时生效

<el-upload drag :auto-upload="false" class="upload-files" multiple accept=".pdf" action="" :file-list="uploadfileList" :on-change="handleChange" :before-remove="handleFileRemove">
   <i class="el-icon-upload"></i>
   <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
<div style="text-align:right;margin-top:10px">
   <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUploadFiles">上传到服务器</el-button>
</div>
    handleChange(file, fileList) {
      this.uploadfileList = fileList;
    },
    handleFileRemove(file, fileList) {
      this.uploadfileList = fileList;
    },
    submitUploadFiles() {
      if (this.uploadfileList.length <= 0) {
        this.$message.error("请选择文件");
        return false;
      }
      var formData = new FormData();
      this.uploadfileList.forEach(file => {
        formData.append("fileList", file.raw);
      });
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }
      batchCaseReportFile(formData, config).then((res) => {
        this.$message.success("上传成功")
        this.uploadfileList= []
      }).catch((err) => {
        this.$message.error(err.msg)
      });
    },

3、使用原生input实现文件上传

 <input type="file" ref="treeFile" class="treeFile" hidden @change="changeName()" />
<el-button size="mini" type="primary" plain @click="uploadFile">选择文件</el-button>
   // 文件资料列表 上传按钮事件
    uploadFile() {
      document.getElementsByClassName("treeFile")[0].click();
    },
    // 文件资料列表 file类型的input
    changeName() {
      var files = document.getElementsByClassName("treeFile");
      if (files[0].files.length !== 0) {
        var formData = new FormData();
        formData.append("file", files[0].files[0]);
        // formData.append("id", this.$route.query.Tid);
        // formData.append("type", this.treeFileType);
        singleFile(formData).then((res) => {
          if (res.status == 200) {
            // 文件数据发生了变化
            
          }
        });
      }
      this.$refs.treeFile.value = null;
    },

二、实现照片墙

1、使用input 封装子组件

父组件中注册并使用子组件

<el-form-item label="上传附件:">
   <div style="width: 470px; ">
     <imgupload :imglist="updateItem.caseAttachFileList" />
  </div>
</el-form-item>
import imgupload from "@/components/MyUpload/imgUpload.vue";
components: {
    imgupload,
  },

 封装子组件imgUpload.vue

<template>
  <div class="myup-root">
    <template v-if="list != undefined">
      <div class="myup-img" v-for="(i, k) in list" :key="k">
        <img :src="i.allFileUrl" alt="" />
        <span class="myup-btns">
          <span class="myup-btn" @click="getPreview(i.allFileUrl)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span class="myup-btn" v-if="!show" @click="getRemove(k)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </template>
    <div class="el-upload el-upload--picture-card" v-if="!show" @click="getInput($event)" v-loading="loading">
      <i class="el-icon-plus" style="cursor: default"></i>
      <input type="file" name="file" ref="file" accept="image/jpeg,image/jpg,image/png" multiple="multiple" @change="getUrl($event)" class="el-upload__input" />
    </div>

    <el-dialog v-dialogDrag append-to-body v-if="dialogImg" :visible.sync="dialogImg">
      <img @click="dialogImg = false" width="100%" :src="ImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { multipleFiles } from "@/api/file";
import { mapGetters } from "vuex";
export default {
  props: {
    imglist: Array,
    show: {
      type: Boolean,
      required: false
    }
  },
  data() {
    return {
      list: [],
      ImageUrl: "",
      dialogImg: false,
      loading: false
    };
  },
  computed: {
    ...mapGetters([
      "HOST"
    ]),
  },
  watch: {
    imglist(oldV, newV) {
      this.list = this.imglist;
    },
    list(oldV, newV) {
      // this.$emit('changeimg')
    }
  },
  mounted() {
    this.list = this.imglist;
  },
  methods: {
    getInput(e) {

      if (e.path[0].children[1]) {
        //触发getUrl
        e.path[0].children[1].click();

      }
    },
    getUrl(e) {
      if (e.target.files.length > 0) {
        // this.getBase64(e.target.files[0]);  //使用base64
        // this.getSingleUrl(e.target.files[0]); //单文件上传
        this.getMultipleUrl(e.target.files); //多文件上传
      }
    },
    getMultipleUrl(files) {
      this.loading = true;
      let _this = this;
      // 多文件上传
      var formData = new FormData();
      for (let i = 0; i < files.length; i++) {
        formData.append("file", files[i]);
        formData.append("type", 1);
      }
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }
      multipleFiles(formData, config).then((res) => {
        if (res.code == 20000) {
          let list = res.data;
          list.forEach(file => {
            // fileUrl只有半截,需要拼接上前半截的路径
            file['allFileUrl'] = this.HOST + file.fileUrl;
            _this.list.push(file)
          });
          this.$refs.file.value = null;
        }
      }).catch((err) => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false;
      });
    },

    getPreview(src) {
      this.ImageUrl = src;
      this.dialogImg = true;
    },
    getRemove(k) {
      this.list.splice(k, 1);
    },
    getSingleUrl(file) {
      this.loading = true;
      // 单文件上传
      let _this = this;
      var formData = new FormData();
      formData.append("file", file);
      singleFile(formData).then((res) => {
        if (res.data.code == 20000) {
          let url = this.HOST + res.data.data.afterName;
          _this.list.push(url);
          this.$refs.file.value = null;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    getBase64(file) {
      let slef = this;
      //把图片转成base64编码
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          // slef.ruleForm.tp = imgResult //在这里图片已经变成base64格式了,你们可以console.log(imgResult),我是放在data里面一个值里面保存起来
          slef.list.push(imgResult);
          // this.moduleArr[key].topics[k].imgSrc.push({src:imgResult})
          resolve(imgResult);
        };
      });
    }
  }
};
</script>

<style scoped>
.myup-root {
  display: flex;
  flex-wrap: wrap;
  width: 470px;
}
.myup-img {
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 108px;
  height: 108px;
  margin: 0 8px 8px 0;
  display: inline-block;
  position: relative;
}
.el-upload--picture-card {
  background-color: rgb(251 253 255);
  border: 1px dashed rgb(192 204 218);
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 108px;
  height: 108px;
  cursor: pointer;
  line-height: 108px;
  vertical-align: top;
}
.el-loading-spinner {
  margin-top: -21px !important;
}
.myup-img img {
  width: 100%;
  height: 100%;
}
.myup-btns {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
}
.myup-btn {
  cursor: pointer;
  text-align: center;
  font-size: 20px;
  margin: 0 5px;
}
.myup-btns:hover {
  opacity: 1;
}
.myup-input {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 108px;
  height: 108px;
  cursor: pointer;
  line-height: 108px;
  vertical-align: top;
  text-align: center;
}
.myup-input:hover {
  border: 1px dashed #c0ccda;
}
.myup-input i {
  font-size: 28px;
  color: #8c939d;
}
</style>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值