需求:
本地实现上传图片和上传文件,(限制大小以及格式),以FormData 格式传递给后端,点击确定按钮时调用接口

实现:
在这里插入图片描述
代码:

<template>
  <div class="dialog-com-box">
    <el-form :model="formDialogCommon" class="demo-form-top">
      <el-form-item label="图片:">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          action="#"
          :before-upload="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <div v-else class="avatar-uploader-icon"> + </div>
          <template #tip>
            <div class="avatar-upload-tip"><span>只支持上传 jpg/png 文件,且不超过 1MB,最多上传1</span></div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="文件:">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="#"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :limit= "1" 
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :http-request="handleProgress"
        >
          <el-button type="primary" @click="UploadTitle='' ">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              仅支持JSON的文件格式(文件小于100MB)
            </div>
            <p v-if="UploadTitle">{{ UploadTitle}}</p>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="dialog-from-button">
      <el-button type="primary" size="small" style="margin-left: 8px;" @click="fromSubmit()"
      >确认</el-button
      >
    </div>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  onMounted,
  ref
} from 'vue'
import type { UploadFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
export default defineComponent({
  name: 'App',
  setup() {
    const UploadTitle = ref()
    const dialogTableVisible = ref(true)
    const imageUrl = ref('')
    const fileList = ref()
    const formData = new FormData()
    // 上传图片 格式大小判断
    const handleAvatarSuccess = (
      file: { type: string; size: number }
    ) => {
      const testmsg = /^image\/(png|jpg|jpeg)$/.test(file.type)
      if (!testmsg) {
        ElMessage.error('上传格式不正确,只支持JPG/PNG!')
        return false
      } else if (file.size && file.size / 1024 / 1024 > 1) {
        ElMessage.error('上传大小不正确,大小不超过1M!')
        return false
      }
      imageUrl.value = URL.createObjectURL(file as any)
      formData.set('files1', file as any) //以formData格式传递图片信息
      if (!imageUrl.value) {
        return false
      }
    }
    // 自定义文件上传时的方法
    const handleProgress = (event: any, file: UploadFile, fileList: UploadFile[]) => {
      // console.log(fileList, file)
    }
    // 上传文件 格式大小判断
    const beforeUpload = (rawFile: { type: string; size: number; name: string;}) => {
      UploadTitle.value = ''
      const fileName = rawFile.name
      const pos = fileName.lastIndexOf('.')
      const lastName = fileName.substring(pos, fileName.length)
      if (
        lastName.toLowerCase() !== '.json'
      ) {
        UploadTitle.value = '上传格式不正确,只支持JSON!'
        return false
      } else if (rawFile.size / 1024 / 1024 > 100) {
        UploadTitle.value = '上传大小不正确,大小不超过100MB!'
        return false
      } else {
        formData.set('files2', rawFile as any) //以formData格式传递文件信息
      }
      return true
    }
    // 上传文件 数量判断 这里设置的只能上传一个文件
    const handleExceed = (files: string|unknown[], fileList: string|unknown[]) => {
      ElMessage.warning(
          `当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
            files.length + fileList.length
          } 个文件`
      )
    }
    // 上传文件移除判断
    const beforeRemove = (file:any) => {
      const fileName = file.name
      const pos = fileName.lastIndexOf('.')
      const lastName = fileName.substring(pos, fileName.length)
      if (file && lastName.toLowerCase() === '.json') {
        return ElMessageBox.confirm(
          `确定移除 ${file.name} ?`, {
            cancelButtonText: '取消',
            confirmButtonText: '确定'
          }
        ).then(async() => {
          ElMessage({
            type: 'success',
            message: '移除成功'
          })
          formData.delete('files2') //删除formData中数据
        })
      }
    }
    // 确认
    const fromSubmit = async() => {
      console.log(formData.get('files1'), 'fileData1')
      console.log(formData.get('files2'), 'fileData2')
      // 获取到两条数据,直接传递给接口即可,(files1,files1是接口需要的参数名,直接将formData结合作为参数传递即可)
    }
    onMounted(() => {
      // console.log();
    })
    return {
      dialogTableVisible,
      handleAvatarSuccess,
      imageUrl,
      fileList,
      beforeRemove,
      handleExceed,
      beforeUpload,
      handleProgress,
      fromSubmit,
      UploadTitle
    }
  }
})
</script>

<style lang="less">
    .dialog-com-box {
      text-align: left;
    }
    .el-form-item__label {
        width: 100px;
        text-align: left;
        // border: 1px solid red;
    }
    .upload-demo{
        display: flex;
        flex-flow: wrap;
        .el-upload__tip{
            width: 90%;
        }
        p{
            color: red;
            width: 100%;
        }
        .el-upload-list{
          width: 70%;
        }
    }
  .avatar-uploader {
    display: flex;
    .el-upload {
        border: 1px dashed #8c939d;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 150px;
        height: 150px;
    }
    .avatar-upload-tip {
        display: flex;
        align-items: flex-end;
        margin-left: 20px;
        color: #8c939d;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        font-size: 108px;
        color: #8c939d;
        line-height: 150px;
        text-align: center;
    }
    .avatar {
        width: 150px;
        height: 150px;
        display: block;
    }
}
</style>

Logo

前往低代码交流专区

更多推荐