vue3从本地上传文件给后端(使用ElementPlus)

5,759 阅读1分钟

el-upload部分属性说明

action:上传的后端路径,我使用axios手动传给后端,所以设为了#

:limit:限制上传的文件数

:auto-upload:是否自动上传

:headers:设置请求头,这个一定要设置

:on-change:文件状态改变时会触发,添加文件时被调用

更多的属性详情可以去官网

直接上代码,结合备注很好理解

<el-upload
    class="upload-demo"
    action="#"
    :limit="1"
    :auto-upload="false"
    :headers="headers"
    :on-change="handleChange"
>
  <template #trigger>
    <el-button type="primary">选择文件</el-button>
  </template>
  <template #default style="margin-left: 10px">
    <el-button type="primary" @click="uploadBtn">确定上传</el-button>
  </template>
  <template #tip>
    <div class="el-upload__tip" style="color:red;">
      限制一个文件,下一个文件会覆盖上一个文件
    </div>
  </template>
</el-upload>

<script setup lang="ts">
  let fileUpload = ref()
  // 设置请求头
  const headers = {
    'Content-Type': 'multipart/form-data'
  }
  
  // 选择文件时被调用,将他赋值给fileUpload
  const handleChange = (file: any) => {
    fileUpload.value = file
  }
  
  // 确定上传
  const uploadBtn = async () => {
    let param = new FormData()
    // 如果是多个文件数组就循环添加一下就ok了
    param.append("file", fileUpload.value.raw)
    // 发个后端
    const res = await upLoadCheckProject(param)
    if (res.code === 200) {
      ElMessage({
        message: '上传成功',
        type: 'success'
      })
    } else {
      ElMessage({
        message: '上传失败',
        type: 'error'
      })
    }
  }
</script>