vue3 + ts 项目 结合element 实现自定义上传图片上传文件(限制大小以及格式)FormData 格式

需求:
本地实现上传图片和上传文件,(限制大小以及格式),以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>

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小王和他的小伙伴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值