vue2 + el-upload上传图片/文件,编辑时回显文件名

建议直接复制到本地查看

父组件

<template>
  <div id="recordList">
    <div class="main_search">
      <el-form :inline="true" :model="queryParams" class="search_form">
        <el-form-item label="工程名称">
          <el-input size="small" v-model="queryParams.model.engineeringName" placeholder="检测单位关键字查询" clearable></el-input>
        </el-form-item>
        <el-form-item label="检测日期">
          <el-date-picker :range-separator="null" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" type="daterange" v-model="queryParams.checkTime " value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="验收日期">
          <el-date-picker :range-separator="null" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" type="daterange" v-model="queryParams.receptionTime " value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="录入日期">
          <el-date-picker :range-separator="null" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" type="daterange" v-model="queryParams.createTime " value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="录入人">
          <el-input size="small" v-model="queryParams.model.enteredBy" placeholder="项目名称关键字查询" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <submit-btn :btnName="clickBtn" @searchMethod="handleQuery" @resetMethod="handleReset" :searchAuthority="[]"></submit-btn>
        </el-form-item>
      </el-form>
    </div>
    <div class="main_content">
      <action-btn class="content_search" @addMethod="handleEditSite(editForm,'新增')" @deleteMethod="batchDelete" @exportMethod="exportExcel" :addAuthority="addAuthority" :deleteAuthority="batchDeleteAuthority" :exportAuthority="exportAuthority"></action-btn>
      <el-table @selection-change="handleSelectionChange" :data="recordList" size="mini" :row-class-name="tableRowClassName" :header-cell-style="{
          textAlign: 'center',
          background: '#1C4071',
        }" :cell-style="{ textAlign: 'center' }" :row-style="{ height: '40px' }" border style="width: 100%" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope"><span>{{
              (queryParams.current - 1) * queryParams.size + scope.$index + 1
            }}</span></template>
        </el-table-column>
        <el-table-column prop="projectName" label="所属项目"> </el-table-column>
        <el-table-column prop="engineeringName" label="工程名称"> </el-table-column>
        <el-table-column align="center">
          <template #header v-if="pipeTypeStatus">
            <table-select ref="isEnd" :title="'管网类型'" :label="'name'" :value="'code'" :options="pipeTypeStatus" @confirm-select="handleworkOrderStatusSelect" :multiple="false"></table-select>
          </template>
          <template v-slot="scope">{{
            scope.row.pipeType | valueToLabel(pipeTypeStatus)
          }}</template>
        </el-table-column>
        <el-table-column prop="checkTime" label="检测日期"> </el-table-column>
        <el-table-column prop="receptionTime" label="验收日期"> </el-table-column>
        <el-table-column prop="fileIds" label="监测结果" width="150">
          <template v-slot="scope">
            <div class="result_box" v-for="item in scope.row.resfileUrlList" :key="item.id">
              <!-- <div v-if="item.ext !== 'jpg'" @click="downloadRes(item)">
                {{item.submittedFileName}}
              </div>
              <div v-else>{{item.submittedFileName}}</div> -->
              <span class="detail-file" v-if="item.ext !== 'jpg'" @click="downloadFile(item.url,item.submittedFileName)">{{item.submittedFileName}}</span>
              <!-- <img class="detail-img" v-else :src="item.url" :key="index" @click="downloadIamge(item.url,item.submittedFileName)" /> -->
              <el-image v-else style="width: 100px; height: 100px" :src="item.url" :preview-src-list="scope.row.srcList">
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间"> </el-table-column>
        <el-table-column prop="enteredBy" label="录入人"> </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template v-slot="scope">
            <el-button size="mini" @click="handleEditSite(scope.row,'编辑')" class="edit-button" style="
                margin-right: 10px;
                color: #1e87f0;
                border: 1px solid #1e87f0;
              ">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total.sync="total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getRecordList"></pagination>
    </div>

    <el-dialog :title="editDialogTitle" :visible.sync="editDialogVisible" width="30%" @closed="closeEditSite">
      <el-form :model="editForm" ref="editFormRef" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属项目:" label-width="120px" prop="projectName">
              <div class="project-box" @click="projectDialogVisible = true">
                <el-input class="project-input" placeholder="请选择所属项目" v-model="editForm.projectName"></el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工程名称:" label-width="120px" prop="engineeringName">
              <el-input v-model="editForm.engineeringName" placeholder="请输入工程名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="管网类型:" label-width="120px" prop="pipeType">
              <el-select size="small" v-model="editForm.pipeType" placeholder="请选择管网类型" popper-class="operateDropOption" :popper-append-to-body="true">
                <el-option v-for="(points, ind) in pipeTypeStatus" :key="ind" :label="points.name" :value="points.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测日期:" label-width="120px" prop="checkTime">
              <el-date-picker style="width: 100%;" v-model="editForm.checkTime" type="datetime" placeholder="请选择检测开始时间" :clearable="false" @change="checkTime"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="验收日期:" label-width="120px" prop="receptionTime">
              <el-date-picker style="width: 100%;" v-model="editForm.receptionTime" type="datetime" placeholder="请选择检测开始时间" :clearable="false" @change="checkTime"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="监测成果" label-width="120px" prop="fileIds">
          <div class="foot">
            <fileUpload ref="fileUpload" @getIds="addFileId($event)" :filesList="editForm.resfileUrlList" ></fileUpload>
          </div>
        </el-form-item>
        <el-form-item class="form_footer">
          <el-button size="small" @click="closeEditDialog">取 消</el-button>
          <el-button type="primary" size="small" @click="editFormSub">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 所属项目 弹窗 -->
    <el-dialog :title="projectDialogTitle" :visible.sync="projectDialogVisible" width="50%">
      <project-list @closeProjectSite="closeProjectSite"></project-list>
    </el-dialog>

  </div>
</template>
<script>
import actionBtn from "@/components/buttonView/actionButton";
import submitBtn from "@/components/buttonView/submitBtn";
import recordLists from "./recordLists.vue";
import report from "@/views/saas/statisticsReport/sewagePlant/reportDetail/tableRecord.js";
import maintenanceApi from "@/api/maintenance/emergencySupplies.js";
// import fileUpload from "@/components/saas/fileUpload"
import fileUpload from "./fileUpload.vue";
import projectList from "./projectList.vue"
export default {
  components: {
    actionBtn, submitBtn, recordLists, fileUpload, projectList
  },
  props: {
    keywords: {
      type: String
    }
  },
  computed: {
    pipeTypeStatus() {
      let dicts = this.$store.getters["account/get_dictionary"](["管网类型", "PIPE_TYPE"]);
      console.log('dicts---', dicts)
      return dicts;
    }
  },
  watch: {
    keywords: {
      handler(val) {
        if (val) {
          this.queryParams.equipPlace = val;
          this.tableLists = this.tableLists.filter(item => item.gcdd.indexOf(val) != -1);
          console.log('this.tableData', this.tableLists)
        }
      },
      deep: true,
      immediate: true
    },
    editForm: {
      handler(val) {
        if (val) {
          console.log('ediaosidjfoad', val)
          // this.queryParams.equipPlace = val;
          // this.tableLists = this.tableLists.filter(item => item.gcdd.indexOf(val) != -1);
          // console.log('this.tableData', this.tableLists)
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    let validateFileUrl = (rule, value, callback) => {
      if (!this.hasFmt) {//我控制了FileList 长度代表文件个数
        callback(new Error("请上传文件"))
      } else {
        callback()
      }
    }
    return {
      rules: {
        projectName: [{ required: true, message: "请选择所属项目", trigger: "blur" }],
        engineeringName: [{ required: true, message: "请填写工程名称", trigger: "blur" }],
        pipeType: [{ required: true, message: "请填写管网类型", trigger: "blur" }],
        checkTime: [{ required: true, message: "请选择检测日期", trigger: "blur" }],
        receptionTime: [{ required: true, message: "请选择验收日期", trigger: "blur" }],
        fileIds: [{ required: true, validator: validateFileUrl, trigger: 'change' }]
      },

      loading: false,
      clickBtn: "查询,重置",
      queryParams: {
        current: 1,
        extra: {
          // startTime_st:'',
          // startTime_ed:''
        },
        model: {
          // "projectId": 1517385122993668096
        },
        size: 10,
        sort: "id",
        // order: "descending",
      },
      tableLists: report.record_one,
      tableData: [],
      recordList: [],
      total: 0,
      loading: false,

      addAuthority: [],
      batchDeleteAuthority: [],
      exportAuthority: [],
      editDialogVisible: false,
      editDialogTitle: '',
      editForm: {},
      action: `${process.env.VUE_APP_BASE_API}/activiti/definition/upload`,
      fileLength: [],
      editData: {},
      projectDialogTitle: '',
      projectDialogVisible: false,
      imgUrl: [],
      fileIds: [],
      hasFmt: false,
    }
  },
  created() {
    this.getRecordList()
  },
  methods: {
    async getRecordList() {
      this.loading = true;
      console.log('this.queryParams', this.queryParams)
      let res = await maintenanceApi.pipeCheckRecordPage(this.queryParams);
      console.log(res);
      if (res.success && res.data && res.data.records) {
        this.recordList = res.data.records || [];
        this.recordList.forEach((element, index) => {
          if (element.fileIds) {
            this.getFileIds(this.recordList[index].fileIds, index)
          }
        });
        this.total = Number(res.data.total);
      }
      this.loading = false;
    },
    async getFileIds(ids, index) {
      this.recordList[index].srcList = []
      let res = await maintenanceApi.getFindByIds(ids)
      if (res.code == 0 && res.data) {
        res.data.forEach((ele)=>{
          ele.name = ele.submittedFileName
        })
        this.$nextTick(() => {
          this.$set(this.recordList[index], "resfileUrlList", res.data)
          res.data.forEach((ele, ele_index) => {
            if (ele.ext == 'jpg') {
              this.recordList[index].srcList.push(ele.url)
            }
          })
        })
      }
    },
    // 查询按钮操作
    handleQuery() {
      if (this.queryParams.checkTime) {
        this.queryParams.extra.checkTime_st = this.$dayjs(this.queryParams.checkTime[0]).format("YYYY-MM-DD HH:mm:ss")
        this.queryParams.extra.checkTime_ed = this.$dayjs(this.queryParams.checkTime[1]).format("YYYY-MM-DD HH:mm:ss")
      }
      if (this.queryParams.receptionTime) {
        this.queryParams.extra.receptionTime_st = this.$dayjs(this.queryParams.receptionTime[0]).format("YYYY-MM-DD HH:mm:ss")
        this.queryParams.extra.receptionTime_ed = this.$dayjs(this.queryParams.receptionTime[1]).format("YYYY-MM-DD HH:mm:ss")
      }
      if (this.queryParams.createTime) {
        this.queryParams.extra.createTime_st = this.$dayjs(this.queryParams.createTime[0]).format("YYYY-MM-DD HH:mm:ss")
        this.queryParams.extra.createTime_ed = this.$dayjs(this.queryParams.createTime[1]).format("YYYY-MM-DD HH:mm:ss")
      }
      this.getRecordList();
    },

   
    // 重置按钮操作
    handleReset() {
      this.queryParams = {
        current: 1,
        extra: {},
        model: {},
        size: 10,
        sort: "id",
      }
      this.getRecordList();
    },
    // 点击新增/编辑按钮,弹出页面
    handleEditSite(row, type) {
      this.editFormState = type
      if (row.resfileUrlList) {
        this.resfileUrlList = row.resfileUrlList
      }
      this.editForm = { ...row }; //解构对象赋值
      console.log('this.editForm', this.editForm)
      this.editDialogVisible = true;
    },

    batchDelete() {
      let ids = [];
      if (this.multipleSelection === undefined) {
        this.$message({
          type: "warning",
          message: "请勾选需要删除的内容!",
        });
      } else {
        this.multipleSelection.forEach((item, index) => {
          ids.push(item.id);
        });
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const res = await maintenanceApi.delPush({ 'ids[]': ids.toString() });
          if (res.success) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getRecordList();
          }
        });
      }
    },
    async exportExcel() {
      let params = {
        current: 1,
        extra: {},
        model: {
          contentTypeCode: "",
          contentTypeLable: this.pushForm.content,
          cron: "",
          cycleDatetime: "",
          cycleType: "",
          roleIds: "",
          roleNames: "",
          sendTypeCode: "",
          sendTypeLable: this.pushForm.type,
        },
        order: "descending",
        size: 10,
        sort: "id",
      };
      this.$confirm("此操作将导出文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await pushApi.exportPush(params);
        downloadFile(res);
        if (res) {
          this.$message({
            type: "success",
            message: "导出成功!",
          });
        }
      });
    },
    // 关闭编辑弹窗事件
    closeEditSite() {
      this.editForm = {};
      this.editDialogVisible = false;
    },
    handleSelectionChange(value) {
      this.multipleSelection = value;
    },
   
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "warning-row"; //类名
      } else {
        return "success-row"; //类名
      }
    },
    
    // 关闭编辑弹窗事件
    closeEditDialog() {
      this.editForm = {};
      this.editDialogVisible = false;
      this.rules.projectName.required = true
    },

    closeProjectSite(row) {
      this.editForm.projectName = row.name
      this.editForm.projectId = row.id
      this.projectDialogVisible = false;
    },
    async editFormSub() {
      this.$refs["editFormRef"].validate(async (valid) => {
        console.log('valid', valid)
        this.editForm.fileIds = this.fileIds.join(',');
        console.log('this.editForm', this.editForm)
        if (this.fileIds.length > 0) {
          this.hasFmt = true;
        }
        if (valid) {
          const res = await maintenanceApi.pipeCheckRecord(this.editForm);
          if (res.success) {
            this.$message.success("新增成功");
            this.getRecordList()
            this.closeEditDialog();
          }
        }
      });
    },
    checkTime() {
      var start = new Date(this.editForm.checkTime).getTime()
      var end = new Date(this.editForm.receptionTime).getTime()
      if (start > end) {
        this.msgError(this.$t('开始时间不能大于结束时间'))
        this.editForm.receptionTime = undefined
      }
    },
    async addFileId(fileId) {
      this.fileIds.push(fileId);
      if (this.fileIds.length > 0) {
        this.hasFmt = true;
      }
    },
    handleworkOrderStatusSelect(value) {
      this.queryParams.model.pipeType = value;
      this.getRecordList();
    },
    downloadRes(row) {
      window.location.href = row.url
    },
    /**
 * @param imgSrc 图片地址
 * @param name 图片名称
 */
    downloadIamge(imgSrc, name) {
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgSrc;
    },
    /**
     * @param src 文件地址
     * @param name 文件名称
     */
    downloadFile(src, name) {
      let x = new XMLHttpRequest();
      x.open("GET", src, true);
      x.responseType = 'blob';
      x.onload = function (e) {
        let url = window.URL.createObjectURL(x.response)
        let a = document.createElement('a');
        a.href = url
        a.download = name
        a.click()
      }
      x.send();
    }
  }
}
</script>

子组件

<template>
  <div>
    <el-upload ref="upload" :headers="headers" :action="uploadActionUrl"
     multiple :limit="3" :on-exceed="handleExceed" :on-error="uploadError"
      :on-success="uploadSuccess" :on-remove="onRemoveTxt" :before-upload="onBeforeUpload"
       :file-list="files" accept=".jpg,.png,.pdf,.doc,.xls,.xlsx">
      <img src="@/assets/icon_添加附件.png" alt="" class="hehe" />
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import db from "@/utils/localstorage";
import { Base64 } from "js-base64";
export default {
  props:['filesList'],
  data() {
    return {
      uploadActionUrl: `${process.env.VUE_APP_BASE_API}/file/attachment/upload`,
      files: [
            // {
            //   "id": "1519126174771445760",
            //   "createTime": "2022-04-27 09:27:59",
            //   "createdBy": "3",
            //   "echoMap": null,
            //   "updateTime": "2022-04-27 09:27:59",
            //   "updatedBy": "3",
            //   "bizId": null,
            //   "bizType": "",
            //   "dataType": {
            //     "code": "DOC",
            //     "desc": "鏂囨。"
            //   },
            //   "submittedFileName": "新建PDF文档.pdf",
            //   "name": "新建PDF文档.pdf",
            //   "group": "",
            //   "path": "",
            //   "relativePath": "_NONE\\2022\\04",
            //   "url": "http://192.168.0.86:9760/api/file/_NONE/2022/04/9822123c-5e43-448d-be8a-102d7dda1478.pdf",
            //   "fileMd5": "",
            //   "contextType": "application/pdf",
            //   "filename": "9822123c-5e43-448d-be8a-102d7dda1478.pdf",
            //   "ext": "pdf",
            //   "size": "1503",
            //   "orgId": null,
            //   "icon": "el-icon-question",
            //   "createMonth": "2022年04月",
            //   "createWeek": "2022年18周",
            //   "createDay": "2022年04月27日"
            // }
      ],
      hehe: "",
    };
  },
  computed: {
    headers() {
      return {
        token: "Bearer " + db.get("TOKEN", ""),
        tenant: db.get("TENANT", "") || "",
        Authorization: `Basic ${Base64.encode(
          `${process.env.VUE_APP_CLIENT_ID}:${process.env.VUE_APP_CLIENT_SECRET}`
        )}`,
      };
    },
  },
  watch :{
    filesList: {
      handler(val) {
        console.log('val',val)
        this.files = val
      },
      deep: true,
      immediate: true
    },
  },
  created(){
    this.files = this.filesList || []
    console.log('files',this.files)
  },
  methods: {
    resetFile() {
      this.$refs.upload.clearFiles();
    },
    handleExceed() {
      console.log("11");
    },
    uploadError() {
      console.log("22");
    },
    uploadSuccess(res) {
      console.log(res);
      if (res.success) {
        this.$emit("getIds", res.data.id);
      }
    },
    onRemoveTxt() {
      console.log("44");
    },
    onBeforeUpload() {
      console.log("55");
    },
  },
};
</script>

<style lang="scss" scoped>
.hehe {
  margin-right: 6px;
}
</style>

界面样式

在这里插入图片描述

编辑弹窗界面样式

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
当然可以!下面是一个使用Vue、Axios和Element UI的例子,实现.csv文件上传的过程。 首先,你需要安装Vue、Axios和Element UI依赖,可以通过以下命令进行安装: ``` npm install vue axios element-ui ``` 然后,在你的Vue组件中,你可以按照以下的方式使用`el-upload`组件来实现.csv文件上传的功能: ```html <template> <div> <el-upload action="/upload" <!-- 上传文件的接口地址 --> :on-success="handleSuccess" <!-- 上传成功的回调函数 --> :before-upload="beforeUpload" <!-- 上传文件之前的回调函数 --> > <el-button>点击上传</el-button> </el-upload> </div> </template> <script> import axios from 'axios'; export default { methods: { beforeUpload(file) { // 判断文件类型是否为.csv const fileType = file.type; const isCSV = fileType === 'text/csv'; if (!isCSV) { this.$message.error('只能上传.csv文件'); } return isCSV; }, handleSuccess(response) { // 上传成功后的处理逻辑 // 在这里可以对服务器返回的数据进行操作 console.log(response); } } } </script> ``` 在上述代码中,我们使用了`el-upload`组件来创建一个文件上传的区域。通过设置`action`属性来指定文件上传的接口地址,`on-success`属性来指定上传成功后的回调函数。同,我们还使用了`before-upload`属性来实现对文件类型的限制,只允许上传.csv文件。 在`beforeUpload`方法中,我们通过判断文件的`type`属性是否为`text/csv`来确定文件类型是否为.csv。如果不是,则会弹出错误提示。如果是,则返回`true`,允许文件上传。 在`handleSuccess`方法中,我们可以对服务器返回的数据进行操作。你可以根据实际需求进行处理。 最后,你需要在你的后端服务器中实现一个接口来接收上传的文件,并进行相应的处理。你可以使用任何你熟悉的后端技术来实现这个接口。 希望这个例子对你有所帮助!如果有任何问题,请随问我。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值