el-table列表上传附件

<template>
  <div class="listBasisListAdd">
    <h3 style="margin-left:20px">{
    
    {
    
    formTitle}}</h3>
    <el-divider></el-divider>
    <el-form ref="formData" :model="formData" :rules="formDataRules" :key="'X'+Xindex" label-width="150px" class="demo-ruleForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位:" prop="comName">
            <span>{
    
    {
    
    formData.comName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="列表:" prop="infoArrayDTOList">
            <el-button type="text" @click="handleAdd('列表')">添加</el-button>
            <el-table :data="formData.infoArrayDTOList" height="400" class="box" :header-cell-style="{ background: 'rgb(242, 242, 242)' }" row-key="id" border fit highlight-current-row style="margin-top: 10px;">
              <el-table-column type="index" label="序号" width="50" align="center"> </el-table-column>
              <el-table-column prop='ruleName' label='清单信息' align="center" :render-header="addRedStar">
                <template slot-scope="scope">
                  <el-form-item :prop="'infoArrayDTOList.' + scope.$index + '.ruleName'" :rules="formDataRules.ruleName">
                    <el-input type="textarea" autosize v-model="scope.row.ruleName" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop='appendId' label='附件' align="center" :render-header="addRedStar">
                <template slot-scope="scope">
                  <el-form-item :prop="'infoArrayDTOList.' + scope.$index + '.appendId'">
                    <a id="a1111">
                      <span style="cursor:pointer" v-for=" (item,index) in scope.row.appendId " :key="index" @click="appendIdDownLoad(item,'a1111')">
                        {
    
    {
    
    index!=0?",":""}} {
    
    {
    
    item.name}}
                      </span>
                    </a>
                    <div>
                      <el-button size="small" type="text" @click="uploadDialog(scope.$index)">上传文件</el-button>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="" label="操作" align="center" width="80">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click.native.prevent="handleDelete('列表',scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align:right;">
          <el-form-item>
            <el-button type="primary" style="background:#169BD5" @click="saveForm('formData','保存')">保存</el-button>
            <el-button @click="cancleForm('formData')">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog v-if="uploadDialogVisible" title="上传附件" :visible.sync="uploadDialogVisible" width="40%" top="10vh">
      <el-form ref="ruleForm" :model="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件:" prop="attachmentVos">
              <div style="display:inline-block;" :key="'p'+pindex">
                <el-tag v-for="item in ruleForm.attachmentVos" :key="item.uuid?item.uuid:item.id" closable :disable-transitions="false" @close="handleClose(item)" style="margin-right:3px;">
                  {
    
    {
    
    item.name}}
                </el-tag>
              </div>
              <el-upload class="upload-demo" :style="ruleForm.attachmentVos.length==0?'margin-top: -40px;':''" :ref="`Uploader-${uploadId}`" :name="uploadId" :auto-upload="false" action="#" :http-request="annexUploads" multiple :on-preview="handlePreview" :on-success="handleSuccess" :on-change="changeUpload" :on-remove="handleRemove" :file-list="fileList" accept=".rar,.zip,.wps,.doc,.docx,.pdf,.xls,.xlsx,.jpg" :show-file-list="false">
                <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持文件格式:.rar .zip .wps .doc .docx .pdf .xls .xlsx .jpg</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align:right;">
            <el-form-item>
              <el-button type="primary" style="background:#169BD5" @click="uploadOkClick">确定</el-button>
              <el-button @click="uploadCancleClick">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
    
     complianceListAdd, uploadFile, downFile } from "@/api/complianceChecklist";
export default {
    
    
  components: {
    
     },
  data() {
    
    
    return {
    
    
      addRedStar(h, {
     
      column }) {
    
    
        // 给表头加必选标识
        return [
          h("span", {
    
     style: "color: red" }, "*"),
          h("span", " " + column.label),
        ];
      },
      formTitle: "新增",
      formData: {
    
    
        comName: "",
        infoArrayDTOList: [],
      },
      formDataRules: {
    
    
        ruleName: [{
    
     required: true, message: "不能为空", trigger: "change" }],
      },

      uploadDialogVisible: false,
      uploadDialogIndex: null,

      fd: new FormData(),
      uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),
      fileList: [],
      uploadFiles: [], //待上传的文件列表
      fileTotal: 0, //上传文件总数
      pindex: 0,
      currentUploadNum: 0,
      ruleForm: {
    
    
        attachmentVos: [],
      },
      Xindex: 0,

    };
  },
  // 监听属性 类似于data概念
  computed: {
    
    },
  // 监控data中的数据变化
  watch: {
    
    
    test: {
    
    
      deep: true, // deep: true  // 可以深度检测到 test 对象的属性值的变化
      handler(newV) {
    
    
        // this.test = newV;
      },
    },
  },
  // 生命周期 - 创建完成(可以访问当前this实例)
  created() {
    
    
    let that = this;
  },
  // 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    
    },
  // 方法集合
  methods: {
    
    
    // 列表-添加
    handleAdd(val) {
    
    
      let obj = {
    
    
        ruleName: "",
        appendId: [],
      };
      if (val == "要求清单内容") {
    
    
        this.formData.infoArrayDTOList.push(obj);
      }
    },
    // 列表-删除
    handleDelete(val, index) {
    
    
      if (val == "列表") {
    
    
        this.formData.infoArrayDTOList.splice(index, 1);
      }
    },
    // 保存
    saveForm(ruleForm, val) {
    
    
      this.$refs[ruleForm].validate((valid) => {
    
    
        if (valid) {
    
    
          let params = JSON.parse(JSON.stringify(this.formData))
          complianceListAdd(params).then((res) => {
    
    
            console.log("res11新增", res);
            if (res.code == "200") {
    
    
              this.$message.success("新增成功");
              this.cancleForm()
            } else {
    
    
              this.$message.error(res.message);
            }
          }).catch((err) => {
    
    
          })
        } else {
    
    
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消
    cancleForm() {
    
    
      this.$router.go(-1)
    },
    // 点击列表中的上传
    uploadDialog(index) {
    
    
      this.uploadDialogVisible = true
      this.uploadDialogIndex = index
      this.ruleForm.attachmentVos = JSON.parse(JSON.stringify(this.formData.infoArrayDTOList[this.uploadDialogIndex].appendId))
    },
    // 确定
    uploadOkClick() {
    
    
      this.formData.infoArrayDTOList[this.uploadDialogIndex].appendId = this.ruleForm.attachmentVos
      this.Xindex = Math.random().toString(36).substr(2).toLocaleUpperCase()
      this.uploadDialogVisible = false
    },
    // 取消
    uploadCancleClick() {
    
    
      this.uploadDialogVisible = false
    },
    // 下载
    appendIdDownLoad(row, val) {
    
    
      let params = {
    
    
        url: row.url
      }
      console.log("val", val);
      downFile(params)
        .then((res) => {
    
    
          console.log('res', res)
          document.getElementById(val).href = res.data
          document.getElementById(val).download = true
          document.getElementById(val).click()
          console.log("urlhref", document.getElementById(val));
        })
        .catch((err) => {
    
    
        });
    },
    // 附件资料--------开始
    handleSuccess(response, file, fileList) {
    
    
      console.log("成功了", response, file, fileList);
    },
    submitUpload() {
    
    
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
    
    
      console.log(file, fileList);
    },
    handlePreview(file) {
    
    
      console.log("file", file);
    },
    changeUpload(file, fileList) {
    
    
      console.log("file", file, fileList, fileList[fileList.length - 1]);
      //获取添加文件进来的状态
      file.status == "ready" && this.uploadFiles.push(file.raw);
      //获取原始文件的个数
      this.fileTotal = document.getElementsByName(this.uploadId)[0].files.length;
      //如果原始文件和upload的个数相同的时候就说明已经添加完了,可以触发上传的方法了
      if (this.uploadFiles.length === this.fileTotal) {
    
    
        //获取上传文件的组件
        const Uploader = this.$refs[`Uploader-${
      
      this.uploadId}`];
        //触发上传文件列表的方法
        Uploader.submit();
        this.currentUploadNum = 0
      }
    },
    annexUploads(file) {
    
    
      console.log("file", file);
      // let fd = new FormData();
      this.fd.append("multipartFile", file.file);
      this.currentUploadNum++
      if (this.currentUploadNum === this.fileTotal) {
    
    
        // this.fd.append("type", "1");
        uploadFile(this.fd)
          .then((res) => {
    
    
            if (res.code == "200") {
    
    
              this.$message.success("附件上传成功");
              res.data.forEach((item, index) => {
    
    
                let current = JSON.parse(JSON.stringify(item))
                let name = current.split("/")[current.split("/").length - 1]
                let nameList = name.split(".")
                let dataObj = {
    
    
                  name: nameList[0].substring(0, nameList[0].length - 13) + "." + nameList[1],
                  url: item
                }
                this.ruleForm.attachmentVos.push(dataObj);
              });
              this.uploadFiles = [];
              this.fileList = [];
              this.fd = new FormData();
            } else {
    
    
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
    
    
            this.uploadFiles = [];
            this.fd = new FormData();
          });
      }
    },
    // 项目内容--项目资料---删除
    handleClose(tag) {
    
    
      this.$confirm("是否确定删除这个文件?", "删除", {
    
    
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(() => {
    
    
          this.ruleForm.attachmentVos.splice(
            this.ruleForm.attachmentVos.indexOf(tag),
            1
          );
          this.pindex++
          this.$message.success('删除成功');
        })
        .catch(() => {
    
    
          this.$message.info('已取消删除');
        });
    },
    // 附件资料--------结束
  },


};
</script>

<style >
.listBasisListAdd {
    
    
  background: #fff;
  padding: 0 20px 20px;
}
.el-row {
    
    
  display: flex;
  flex-wrap: wrap;
}
.el-table .el-form-item__error {
    
    
  padding-top: 1px;
}
.el-table .el-form-item__content {
    
    
  margin-bottom: 13px !important;
  margin-top: 13px !important;
}
</style>

猜你喜欢

转载自blog.csdn.net/ingenuou_/article/details/128148446