el-upload基于axios自定义上传formdata文件

需求样式背景效果

1 :选中一张图片后,缩略图的加号按钮消失,hover进图片点击删除后可重新加载图片

  • 默认样式(红色框内)
    在这里插入图片描述

  • 选中样式(选中样式后,默认还是有加号。此处把加号隐藏了)
    在这里插入图片描述

<el-upload
    style="display:inline-block"
    :limit="2" 
    action=''
    list-type="picture-card"
    :on-remove="removeImg"
     :class="ruleForm.preImg.length===0? '':'none'"   // 
    :http-request="changeImg"
    :file-list="ruleForm.preImg">
        <i v-if="ruleForm.preImg.length==0"
         class="el-icon-plus avatar-uploader-icon">
         </i>
</el-upload>


// js

data(){
return {
	ruleForm:{
	  preImg:[],
	  ImgUrl:""
    }
 }	
}
methods:{
    // 缩略图预览去除list
    removeImg(file, fileList) {
      this.ruleForm.preImg = fileList
    },
    // 缩略图预览选择图片
    changeImg(file) {
    // 自定义只能传1个,传第二个给提示要先删除第一个
    if(this.ruleForm.list.length == 1){
        this.$message.warning("Please delete the file first!")
        this.ruleForm.list = [...this.ruleForm.list]
      }else{
        // 获取临时本地url
      this.ruleForm.ImgUrl = window.URL.createObjectURL(file.file)
      // 预览列表重新搞,包括存储文件file
      let obj = { name: file.file.name, url: this.ruleForm.ImgUrl, fileUrl: file.file }
       this.ruleForm.list = [obj]
      }
    },
    // formData 提交
    async addProduct() {
      let fd = new FormData()
      fd.append('files[]', this.ruleForm.preImg[0].fileUrl)
      // this.tableLoading = true
      let res = await this.axiosFormData({
        url:this.uploadApi, // url 需要自己修改
        data:fd
      })
	  // this.tableLoading = false
      if (res.data.msg === "OK" && res.data.code === 200) {
        this.$message.success("上传成功!")
        // this.$emit('change');  
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 封装axios
    async axiosFormData({
	  url, data}){
	  return await axios({
    method: "post",
    //url 需要自己定义
    url : process.env.NODE_ENV === 'development' ? `/dev${url}` : `${apiServe.prodServe}${url}`, 
    data,
    headers: {
      //   Authorization: window.sessionStorage.getItem("token") 
    }
  })
    }
}


// style:
.none /deep/ .el-upload--picture-card {
  display: none;
}

如果需要对file文件校验格式

 let { fileUrl, name } = this.ruleForm.list[0]
      console.log(fileUrl);
      console.log(name);
      // 1. 文件类型效验
      const index = name.lastIndexOf(".");
      const ext = name.substr(index+1);
      if(ext !== 'PDmind'){
        this.$message.warning('file type is not supported!')
        return
      }
      // 2. 做文件大小限制
      const size = fileUrl.size / 1024 / 1024
      if (size > 10) {
        this.$message.warning('import failed! file cannot exceed 10m!')
        return
      }
      // 3. 文件为空效验
      if(size === 0){
        this.$message.warning('file error!')
        return
      }

2022-1-14 补充,场景二

需求背景 :

  1. 支持根据el-upload根据UI图修改成以下样式
  2. 只能传1个文件, 支持自动替换。 与手动删除。 (element的api:on-exceed)
    在这里插入图片描述

父组件

 <ImportFile
      :visible.sync="aboutImport.visible"
      @change="ImportSubmit"
      :title="aboutImport.title"
    ></ImportFile>


data :
       aboutImport: {
        visible: false,
        title: "Import Local File"
      }

methods
    // 导入成功回调
    ImportSubmit () {
      // this.$message.success("修改成功!")
    },

子组件

Options

  1. visible : 是否显示
  2. title : 标题

event :

  1. aboutImport 导入成功
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="487px"
      :before-close="handleClose"
    >
      <div v-loading="tableLoading">
        <div class="dialogBody">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="0"
          >
            <el-form-item
              label
              prop="list"
            >
              <el-upload
                class="upload-demo"
                :limit="1"
                accept=".PDmind"
                :on-remove="removeFile"
                :http-request="changeFile"
                :file-list="ruleForm.list"
                :on-exceed="dragMore"
                drag
                action
                multiple
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  Drag the file here, or
                  <em>click upload</em>
                </div>
                <div
                  class="el-upload__tip"
                  slot="tip"
                >Note: Only PDmind file are supported to import</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div class="bottomBtn">
          <el-button
            round
            style="marginRight:24px"
            @click="handleClose()"
          >Cancel</el-button>
          <el-button
            type="primary"
            round
            @click="submit('ruleForm')"
          >Okay</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { } from "@/request/home"
import uploadMixin from '@/mixin/aLiOss.js';
import { mapMutations, mapGetters } from "vuex";

export default {
  name: "importFile",
  mixins: [uploadMixin],
  components: {},
  data () {
    return {
      tableLoading: false,
      uploadApi: "/api/ProjectFiles/getprojectfiles",
      ruleForm: {
        list: []
      },
      // 表单鉴权
      rules: {
        list: [
          { required: true, message: 'Please select a file to upload', trigger: 'change' }
        ]
      },
      stopForBreakFileStatus: false,
      stopForBreakFileResults: false
    }
  },
  computed: {
    ...mapGetters({
      minder: "getMinder",
      editor: "getEditor",
      tempMindMapData: "getTempMindMapData",
      tempMindMapName: "getTempMindMapName"
    }),
  },
  props: {
    visible: {
      type: Boolean,
    },
    title: {
      type: String,
    }
  },
  methods: {
    ...mapMutations([
      "setTempMindMapName",
      "setTempMindMapData"
    ]),
    removeFile (file, fileList) {
      this.ruleForm.list = fileList
    },
    // 缩略图预览选择文件
    changeFile (file) {
      console.log(file.file);
      // 1. 文件类型效验
      const index = file.file.name.lastIndexOf(".");
      const ext = file.file.name.substr(index + 1);
      if (ext !== 'PDmind') {
        this.$message.warning('Format error! PDMind file only')
        this.ruleForm.list = []
        return
      }
      let ImgUrl = window.URL.createObjectURL(file.file)
      // 预览列表重新搞,包括存储文件file
      let obj = { name: file.file.name, url: ImgUrl, fileUrl: file.file }
      this.ruleForm.list = [obj]
    },
    dragMore (files) {
      let file = files[0]
      let ImgUrl = window.URL.createObjectURL(file)
      // 预览列表重新搞,包括存储文件file
      let obj = { name: file.name, url: ImgUrl, fileUrl: file }
      this.ruleForm.list = [obj]
    },
    // formData 提交
    async addProduct () {
      let { fileUrl, name } = this.ruleForm.list[0]
      console.log(fileUrl);
      console.log(name);
      // 1. 文件类型效验
      const index = name.lastIndexOf(".");
      const ext = name.substr(index + 1);
      let setname = name.substr(0, index);

      if (ext !== 'PDmind') {
        this.$message.warning('Format error! PDMind file only')
        return
      }
      // 2. 做文件大小限制
      const size = fileUrl.size / 1024 / 1024
      if (size > 10) {
        this.$message.warning('Import failed! The file cannot exceed 10M')
        return
      }
      // 3. 文件为空效验
      if (size === 0) {
        this.$message.warning('File error')
        return
      }
      console.log(setname);
      // 4. 做文件长度限制
      console.log(setname.length);
      if (setname.length > 50) {
        setname = setname.substr(0, 50)
      }
      // 5. 损坏文件限制
      this.stopForBreakFileStatus = false
      // 5.1 读取文件
      await this.readerFile(fileUrl)
      let timer = setInterval(async () => {
        if (this.stopForBreakFileStatus) {
          // 读取文件结束
          if(this.stopForBreakFileResults){
            // 未损坏文件
            await this.$message.success('Import successfully')
            this.handleClose();
            this.setTempMindMapData(fileUrl);
            this.setTempMindMapName(setname);
            this.$router.replace({ path: '/supplierAllBack', query: { type: 1 } })
          }
          else{
            // 损坏文件
            this.$message.warning('File error')
          }
          clearInterval(timer)
          
        }
      }, 100)
    },
    readerFile (fileUrl) {
      var reader = new FileReader();
      reader.readAsText(fileUrl, 'utf-8');
      reader.onload = (e) => {
        let resultStr = e.target.result
        console.log(resultStr);
        this.stopForBreakFileResults = /^\{"root":\{"data":/.test(resultStr) && resultStr.includes(`"template":"`) && resultStr.includes(`"theme":"`) && resultStr.includes(`"version":"`)
        this.stopForBreakFileStatus = true
      }

    },
    // 关闭
    handleClose () {
      this.$emit('update:visible', false)
      this.$refs.ruleForm.resetFields();
    },
    // 保存
    submit (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.addProduct()
        } else {
          return false
        }
      })
    },


  },
}
</script>

<style scoped lang="less">
.upload-demo {
  width: 100%;
}
/deep/ .el-upload {
  width: 100%;
}
/deep/ .el-upload-dragger {
  width: 100%;
  height: 230px;
  background-color: #f5f4ff;
  border: 1.5px dashed #c4c4ff;
}
/deep/ .el-upload-dragger .el-upload__text {
  font-family: Inter;
  font-weight: 500;
  font-size: 16px;
}
/deep/ .el-upload-dragger .el-upload__text em {
  color: #5452f6;
}
/deep/ .el-icon-upload:before {
  content: "";
  background: url("../../../../imgs/folder.png") center no-repeat;
  display: inline-block;
  width: 100px;
  height: 70px;
  margin-bottom: -30px;
}
/deep/ .el-upload-list__item:hover {
  background-color: #f5f4ff;
}
/deep/ .el-upload-list__item {
  line-height: 2.8;
}
/deep/ .el-upload-list__item .el-icon-close {
  top: 12px;
}
/deep/ .el-upload-list__item .el-icon-close-tip {
  opacity: 0;
}
.bottomBtn {
  margin-top: 36px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值