官方文档链接

官方文档 https://element.eleme.cn/#/zh-CN/component/upload

使用el-upload组件上传文件

在这里插入图片描述

具体参数说明,如何实现上传、下载、删除等功能

  • action:文件上传地址,我的项目里已经封装好了请求。使用的时候需要依据项目填写。

  • show-file-list: 是否显示已上传文件列表。

  • headers:设置上传的请求头部。我的项目需要传token。

  • on-preview:点击文件列表中已上传的文件时的钩子。
    可以在这个这个回调方法里写下载功能部分代码,实现点击文件下载功能。

  • on-remove:文件列表移除文件时的钩子。
    在文件列表回显时,使用数组fileData记录id列,执行删除回调时,匹配id,因为删除回调方法返回的file中不记录id,只记录url,可通过url相同返回id,再调用删除接口。

  • on-successfunction(response, file, fileList) 文件上传成功时的钩子。
    如果不设置auto-upload:false ,则选取文件后立即进行上传,成功回调后使用返回的参数调用接口,完成文件上传。

获取文件列表进行file-list格式匹配

  • file-list :上传的文件列表, 例如: [{name: ‘food.jpg’, url: ‘https://xxx.cdn.com/xxx.jpg’}]
  • 列表回显时,需要将返回列表对应参数赋值给file-list对应的数组fileData 。

代码

<template>
  <basic-container>
    <el-form :model="dataForm" ref="dataForm" label-width="140px">
      <el-form-item>
        <el-upload class="upload-demo" 
          ref="upload" 
          :headers="headers" 
          action="/admin/sys-file/upload"
          :on-preview="handlePreview" 
          :on-remove="handleRemove" 
          :on-success="handleAvatarSuccess" 
          :file-list="fileData">
          <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </basic-container>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj,
    fetchList,
    getnoticeId,
    delObj
  } from '@/api/policy/noticeattachment'
  import store from '@/store'
  import {mapState} from 'vuex'
  export default {
    data() {
      return {
        dataForm: {
          id: 0,
          noticeId: '',
          attachName: '',
          attachUrl: '',
        },
        dataList: [],
        fileData: [],
        headers: {
          'Authorization': 'Bearer ' + store.getters.access_token,
        },
      }
    },
    methods: {
      init(id) {
        // console.log(id)
        this.dataForm.noticeId = id
        //数组每次需要清空
        this.fileData.splice(0, this.fileData.length);
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields();
          if (this.dataForm.noticeId) {
            getnoticeId(this.dataForm.noticeId).then(response => {
              this.dataList = response.data.data;
              this.dataList.forEach(list => {
                this.fileData.push({
                  name: list.attachName,
                  url: list.attachUrl,
                  id: list.id //删除时使用
                })
              })
            });
          }
        });
      },
      //移除回调
      handleRemove(file, fileList) {
        let resultArr = this.fileData.filter((item) => {
          return item.url === file.url
        });
        // console.log(resultArr[0])
        this.dataForm.id = resultArr[0].id
        this.$nextTick(() => {
          this.deleteHandle(this.dataForm.id)
        })
      },
      //点击文件列表中已上传的文件时的钩子
      handlePreview(file) {
        console.log(file);
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.download = file.name;
        a.href = file.url;
        a.dispatchEvent(event);
      },
      //成功回调
      handleAvatarSuccess(res, file, fileList) {
        this.dataForm.attachName = file.name
        this.dataForm.attachUrl = res.data.url
        this.dataFormSubmit()
      },
      // 删除
      deleteHandle(id) {
        delObj(id).then(data => {
          this.$message.success('删除成功')
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(data => {
                this.$message.success('修改成功')
              });
            } else {
              addObj(this.dataForm).then(data => {
                this.$message.success('添加成功')
              })
            }
          }
        })
      }
    }
  }
</script>

文件展示列表自定义为表格展示

在这里插入图片描述

使用的具体参数说明

  • show-file-list: 是否显示已上传文件列表。
    展示自定义表格样式需要设置show-file-list=“false”
  • on-successfunction(response, file, fileList) 文件上传成功时的钩子。
    如果不设置auto-upload:false ,则选取文件后立即进行上传,成功回调后使用返回的参数调用接口,完成文件上传。

文件大小展示问题(KB/MB)

  • 上传文件时size默认传file返回的size大小(默认为1字节),在表格展示时进行判断,如果大于1MB展示单位为MB,小于1MB展示单位KB。
  • MB:size / 1024 / 1024
  • KB:size / 1024
    (既然提到字节,可能有的人不熟悉字节,这里顺便记录一下字节转换关系)
    字节也叫Byte,是计算机数据的基本存储单位。
    8bit(位)=1Byte(字节)
    1024Byte(字节)=1KB
    1024KB=1MB
    1024MB=1GB
    1024GB=1TB
    其中:K是千 M是兆 G是吉咖 T是太拉。

文件下载

  • 点击下载按钮,实现下载此文件。使用a标签,传入对应文件name和url。具体代码下面记录。

代码

<template>
  <basic-container>
        <el-upload class="upload-demo"
          ref="upload"
          :headers="headers"
          action="/admin/sys-file/upload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false">
          <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
        </el-upload>
        <el-table class="down" :data="dataList" border stripe style="width: 100%;margin-top: 20px;">
            <el-table-column prop="attachName" label="文件名称"></el-table-column>
            <el-table-column prop="attachSize" label="文件大小">
              <template slot-scope="scope">
                  <span v-if="scope.row.attachSize / 1024 / 1024 < 1">{{(scope.row.attachSize / 1024).toFixed(2) + 'KB'}}</span>
                  <span v-else>{{(scope.row.attachSize / 1024 / 1024).toFixed(2) + 'MB'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="上传时间"></el-table-column>
            <el-table-column width="150px" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="text">
                        <a @click="downloadFile(scope.row.attachName,scope.row.attachUrl)">下载</a>
                    </el-button>
                    <el-button size="small" type="text" @click="deleteHandle(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-form>
  </basic-container>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj,
    fetchList,
    getnoticeId,
    delObj
  } from '@/api/policy/noticeattachment'
  import store from '@/store'
  import {mapState} from 'vuex'
  export default {
    data() {
      return {
        dataForm: {
          id: 0,
          noticeId: '',
          attachName: '',
          attachUrl: '',
          attachSize: '',
        },
        dataList: [],
        headers: {
          'Authorization': 'Bearer ' + store.getters.access_token,
        },
      }
    },
    methods: {
      init(id) {
        this.dataForm.noticeId = id
        this.$nextTick(() => {
          if (this.dataForm.noticeId) {
            this.getDataList()
          }
        });
      },
      //获取附件列表
      getDataList(){
        getnoticeId(this.dataForm.noticeId).then(response => {
          this.dataList = response.data.data;
        });
      },
      //下载按钮回调
      downloadFile(name,url){
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.download = name;
        a.href = url;
        a.dispatchEvent(event);
      },
      //成功回调
      handleAvatarSuccess(res, file, fileList) {
        this.dataForm.attachName = file.name
        this.dataForm.attachUrl = res.data.url
        this.dataForm.attachSize = file.size
        this.dataFormSubmit()
      },
      // 删除
      deleteHandle(id) {
        this.$confirm('是否确认删除该附件', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(id)
        }).then(data => {
          this.$message.success('删除成功')
          this.getDataList()
        })
      },
      // 表单提交
      dataFormSubmit() {
        addObj(this.dataForm).then(data => {
          this.$message.success('添加成功')
          this.getDataList()
        })
      }
    }
  }
</script>
<style lang="scss" scoped="scoped">
  .down >>> a {
    color: #409EFF;
  }
</style>

上传文件大小与文件类型校验

  1. 可以在beforeUpload方法中进行过滤。
  2. 使用accept参数

我自己的项目里暂时没有限制,后续有需求的话会进行更新。这里不做过多概述。
下面po官网代码:

<el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

<script>
  export default {
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>

差不多使用到的就这些啦,如果有新需求会继续记录。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐