vue3+Element-Plus上传文件,并传递额外参数

3,472 阅读1分钟

需求:

  1. 文件上传
  2. 额外参数传递

方式1:

<template>
    <el-upload
      ref="uploadRef"
      action
      :limit="1"
      accept=".json"
      :headers="upload.headers"
      :disabled="upload.isUploading"
      :http-request="handleUploadFile"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">上传json文件,且只能上传 1 个文件</div>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFile">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

/*** 应用数据导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() }
})

// 导入应用数据
function handleImport(row: any) {
  upload.title = '应用数据导入'
  upload.open = true
}
/**文件上传中处理 */
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  upload.isUploading = true
}
// 处理上传文件
const handleUploadFile = async (param: any) => {
  // console.log(param, 99999);
  let formData = new FormData()
  formData.append('file', param.file)
  formData.append('appType', '2') // 额外参数
  await appDataImport(formData)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + '上传成功' + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
}

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].clearFiles()
  // ***********************************重新请求应用数据*********************************
  getList()
}
/** 提交上传文件 */
function submitFile() {
  proxy.$refs['uploadRef'].submit()
}
</script>

上传文件,同时传递额外参数 需要使用到 let formData = new FormData() image.png

方式2:

image.png

image.png 费劲九牛二虎之力,用方式1写完后,发现可以直接使用:data属性直接传递额外参数,还是要仔细看文档啊,希望本文对您有所帮助!