element的el-upload同时上传图片和视频(手动上传)

本文介绍了一个基于Element UI的视频发布组件实现细节,包括如何验证上传的视频封面和视频文件格式及大小,确保用户输入的有效性,并通过表单验证机制完成视频的提交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现效果图如下
在这里插入图片描述

  <el-dialog
        title="发布视频"
        :visible.sync="publishDialogVisible"
        width="80%"
        :before-close="handleClose"
        center
        v-dialogDrag
        :close-on-click-modal="false"
        top="6vh"
      >
        <el-form
          ref="uploadform"
          :model="uploadform"
          :rules="uploadformrules"
          label-width="auto"
          label-position="top"
        >
          <el-form-item
            label="视频标题:"
            prop="name"
          >
            <el-input v-model="uploadform.name"></el-input>
          </el-form-item>
          <el-form-item
            label="视频封面:"
            prop="imageFile"
          >
            <el-upload
              class="avatar-uploader"
              action=""
              ref="upload"
              :show-file-list="false"
              :auto-upload="false"
              accept=".png,.jpg,.jpeg"
              :on-change="imageChange"
            >
              <img
                v-if="imgUrl!=''"
                class="avatar"
                :src="imgUrl"
                alt=""
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>

            </el-upload>
          </el-form-item>
          <el-form-item
            label="上传视频:"
            prop="fileList"
          >
            <el-upload
              ref="uploadFile"
              name="files"
              action=""
              :on-change="fileChange"
              accept=".mp4"
              :auto-upload="false"
              :limit="1"
              :on-exceed="uploadExceed"
            >
              <el-button
                type="primary"
                style="background-color:rgb(9, 180, 197);color:#fff;border:0;"
              >选择视频</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="提交到审核">
            <el-button
              type="primary"
              style="background-color:rgb(9, 180, 197);color:#fff;border:0;"
              @click="publish('uploadform')"
            >
              提交
            </el-button>
          </el-form-item>

        </el-form>
      </el-dialog>

data部分

 uploadform: {
        name: "",
        imageFile: [],
        fileList: [],
      }, //上传视频的表单
      uploadformrules: {
        name: [{ required: true, message: "请输入视频标题", trigger: "blur" }],
        imageFile: [
          { required: true, message: "请选择视频封面", trigger: "change" },
        ],
        fileList: [
          { required: true, message: "请选择视频", trigger: "change" },
        ],
      },
      publishDialogVisible: false, //发布稿件是否可见
      imgUrl: "",

methods

这里重点说明几点,手动上传beforeupload函数不会生效,所以验证文件放在on-change里
在验证文件时我发现不符合要求的文件也会在列表中展示出来,因此使用clearFiles()清除不符合的文件列表
还有视频封面记得保证只有一张,如果用limit限制为1的话就无法切换视频封面(因此通过判断fileList的长度来解决)

//图片改变状态时
    imageChange(file, fileList) {
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        return this.$message.error("上传只能是png,jpg,jpeg格式!");
      }
      if (fileList.length > 1) {
        //始终保证只有一张
        (this.uploadform.imageFile = []), (this.imgUrl = "");
      }
      this.imgUrl = URL.createObjectURL(file.raw);
      this.uploadform.imageFile = file;
    },

    //视频状态改变时
    fileChange(file, fileList) {
      const isMp4 = file.raw.type == "video/mp4";
      const isLt40M = file.raw.size / 1024 / 1024 < 40;
      if (!isMp4) {
        this.$refs.uploadFile.clearFiles();//这里很奇怪我调用输出绑定的uploadform.fileList发现长度是0但是列表还是会有文件显示,调用clearFiles方法后就可以清除错误列表
        return this.$message.error("上传只能是mp4格式!");
      }
      if (!isLt40M) {
       this.$refs.uploadFile.clearFiles();
        return this.$message.error("上传视频只能小于40M!");
      }
      
      this.uploadform.fileList = file;
    },
   //限制文件一次只能上传一个
    uploadExceed() {
      this.$message.error("一次只能上传一个文件!");
    },
    //用户投稿
    publish(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let wfForm = new FormData();
          wfForm.append("title", this.uploadform.name);
          wfForm.append("cover", this.uploadform.imageFile.raw);
          wfForm.append("file1", this.uploadform.fileList.raw);
          publishVideo(wfForm).then((res) => {
            if (res.code != 200) return this.$message.error("投稿失败!");
            this.$message.success("投稿宣传视频成功!");
            this.$refs[formName].resetFields();
            this.$refs.upload.clearFiles();
            this.imgUrl = "";
            this.getlist();
            this.publishDialogVisible = false;
          });
        } else {
          this.$message.error("请填写必备的表单项");
          return false;
        }
      });
    },

css

<style lang="">
.avatar-uploader .el-upload {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: rgb(9, 180, 197);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<think>嗯,用户想用el-upload同时上传图片视频,我得想想怎么实现。首先,我需要回忆一下Element UI的el-upload组件的基本用法。根据用户提供的引用内容,他们之前已经了解过手动上传、覆盖默认上传行为的方法,比如使用http-request或者auto-upload设置为false的情况。 用户的问题是需要同时上传图片视频,可能需要处理不同的文件类型。首先,应该设置accept属性来限制用户只能选择图片视频文件。但是,accept属性可能需要同时包含图片视频的MIME类型,比如image/*video/*。不过,这样可能会让用户选择所有类型的图片视频,可能需要更具体的类型,比如image/png, image/jpeg, video/mp4等。 接下来,上传前的校验。在before-upload钩子中,可以检查文件的类型,是否符合图片视频的格式。比如,如果文件类型不在允许的列表中,就提示用户,并阻止上传。这里可能需要获取文件的type属性,然后判断是否属于image或video下的子类型。 然后,上传的实现。用户可能需要手动上传,也就是选择文件后不自动上传,而是自己处理。这时候需要设置auto-upload为false,然后在某个事件(比如点击按钮)触发时,将文件列表中的文件逐个上传。或者,使用http-request覆盖默认的上传行为,这样可以自定义上传逻辑,比如添加其他参数,分批次处理等。 另外,用户可能需要同时上传多个文件,包括图片视频,所以需要处理多个文件的并发上传。可能需要使用Promise.all来同时处理多个上传请求,或者逐个上传同时,在上传过程中需要显示上传状态,比如进度条,成功或失败的提示。 还有,可能需要限制上传文件的大小,比如图片不超过2MB,视频不超过50MB。这也可以在before-upload中进行校验,如果文件大小超过限制,则提示用户并取消上传。 界面展示方面,可能需要显示已上传图片视频的预览。对于图片,可以使用缩略图;对于视频,可能需要显示视频封面或者默认图标,并允许用户点击播放。此外,上传成功后可能需要隐藏上传按钮,或者限制上传的数量,比如每个类型只能上传一个文件,或者总共上传不超过一定数量。 根据引用中的示例,用户可能已经知道如何手动处理文件列表,比如在on-change事件中更新fileList。这时候,可以维护一个数组,保存所有选择的文件,并在上传时遍历这个数组,分别处理图片视频上传请求。 还有可能需要区分图片视频,分别上传到不同的后端接口。这时候需要在http-request中根据文件类型调用不同的API。例如,图片上传到/image/upload视频上传到/video/upload,并在请求中添加相应的参数。 最后,测试示例代码是否正确,确保图片视频都能正确上传,并且处理各种异常情况,比如网络错误,文件类型错误,大小超限等。</think>以下是如何使用 el-upload 组件实现同时上传图片视频的解决方案: ### 一、实现步骤 1. **文件类型限制** 通过设置 `accept` 属性限定文件类型为图片视频: ```html <el-upload accept="image/*, video/*" :auto-upload="false" :on-change="handleFileChange" :file-list="fileList" > <el-button>选择文件</el-button> </el-upload> ``` 2. **上传前校验** 在 `before-upload` 钩子中校验文件类型大小: ```javascript methods: { beforeUpload(file) { const isMedia = file.type.startsWith('image/') || file.type.startsWith('video/'); const isLt50M = file.size / 1024 / 1024 < 50; if (!isMedia) this.$message.error('仅支持图片视频格式'); if (!isLt50M) this.$message.error('文件大小不能超过50MB'); return isMedia && isLt50M; } } ``` 3. **手动上传实现** 通过自定义 `http-request` 方法处理混合上传: ```html <el-upload :http-request="customUpload" :multiple="true" > <el-button>上传文件</el-button> </el-upload> ``` ### 二、完整示例代码 ```html <template> <div> <el-upload ref="mediaUpload" action="#" :auto-upload="false" :multiple="true" :file-list="fileList" :before-upload="beforeUpload" :on-change="handleFileChange" :http-request="customUpload" accept="image/*, video/*" > <el-button>选择文件</el-button> <template #tip> <div class="el-upload__tip">支持jpg/png/mp4格式,单个文件不超过50MB</div> </template> </el-upload> <el-button @click="submitUpload">立即上传</el-button> </div> </template> <script> export default { data() { return { fileList: [] }; }, methods: { beforeUpload(file) { const isMedia = file.type.startsWith('image/') || file.type.startsWith('video/'); const isLt50M = file.size / 1024 / 1024 < 50; if (!isMedia) this.$message.error('仅支持图片视频格式'); if (!isLt50M) this.$message.error('文件大小不能超过50MB'); return isMedia && isLt50M; }, handleFileChange(file, fileList) { this.fileList = fileList; }, async customUpload(param) { const formData = new FormData(); formData.append('file', param.file); formData.append('type', param.file.type.split('/')[0]); // 区分image/video try { const response = await this.$http.post('/api/upload', formData); param.onSuccess(response); } catch (error) { param.onError(error); } }, submitUpload() { this.$refs.mediaUpload.submit(); } } }; </script> ``` ### 三、关键特性说明 1. **混合文件处理** 通过 `accept="image/*, video/*"` 实现类型过滤,`multiple` 属性支持多选[^1][^2] 2. **分类上传策略** 在 `formData` 中添加类型标识字段,便于后端区分处理媒体类型[^3] 3. **进度反馈优化** 可添加 `on-progress` 事件实现上传进度条显示
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值