Vue+Spring Boot使用ElementUI el-upload实现视频带参数上传(前后端代码详解)

3 篇文章 0 订阅
3 篇文章 0 订阅

前言

在百度上看到很多博主谈起Element UI el-upload大多都是对官网已有内容进行搬运,也仅限前端实现,无后端操作,更无扩展性讲解,千篇一律,枯燥无用,因此今天我给大家讲些有用的,如何实现前端带参数上传视频并接收后端返回的保存路径,后端接收保存前端上传视频并返回保存路径。至于Element UI如何引用,如果你还不会的话,请移步至Element UI官网

Vue实现带参数视频上传

这里先解释下el-upload组件的几个参数含义:
drag: 是否有拖拽框
action:前后端交互的接口
data:上传所带的参数
on-success:文件上传成功时的钩子
before-upload:上传文件之前的钩子,参数为上传的文件
on-progress:文件上传时的钩子

<template>
  <div class="test2">
    <el-upload style="margin-left:14%;margin-top:5%"
      class="avatar-uploader el-upload--text"
      :drag="{Plus}"
      action="http://localhost:8443/api/uploadVidoe3"
      multiple
      :show-file-list="false"
      :data="{SavePath: this.Path.url}"
      :on-success="handleVideoSuccess"
      :before-upload="beforeUploadVideo"
      :on-progress="uploadVideoProcess">
      <i v-if="Plus" class="el-icon-upload"></i>
      <div v-if="Plus" class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
      <div class="el-upload__tip" slot="tip">只能上传mp4/flv/avi文件,且不超过300M</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'test2',
  data () {
    return {
      videoForm: {
        videoId: '',
        videoUrl: ''
      },
      videoFlag: false,
      Plus: true,
      Path: {
        url: 'F:/video/videoUpload'
      },
      videoUploadPercent: 0
    }
  },
  mounted: function () {
  },
  methods: {
    // 视频上传前执行
    beforeUploadVideo (file) {
      const isLt300M = file.size / 1024 / 1024 < 300
      if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) === -1) {
        this.$message.error('请上传正确的视频格式')
        return false
      }
      if (!isLt300M) {
        this.$message.error('上传视频大小不能超过300MB哦!')
        return false
      }
    },
    // 视频上传过程中执行
    uploadVideoProcess (event, file, fileList) {
      this.Plus = false
      this.videoFlag = true
      this.videoUploadPercent = file.percentage.toFixed(0)
    },
    // 视频上传成功是执行
    handleVideoSuccess (res, file) {
      this.Plus = false
      this.videoUploadPercent = 100
      console.log(res)
      // 如果为200代表视频保存成功
      if (res.resCode === '200') {
        // 接收视频传回来的名称和保存地址
        // 至于怎么使用看你啦~
        this.videoForm.videoId = res.newVidoeName
        this.videoForm.videoUrl = res.VideoUrl
        this.$message.success('视频上传成功!')
      } else {
        this.$message.error('视频上传失败,请重新上传!')
      }
    }
  }
}
</script>

Spring Boot接收参数并保存视频

@PostMapping(value = “/api/uploadVidoe3”) 这里接口与前端保持一致

//导包
import java.io.File;
import java.util.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

//实现接收的方法
@CrossOrigin
    @PostMapping(value = "/api/uploadVidoe3")
    @ResponseBody
    public Map<String,String> savaVideotest(@RequestParam("file") MultipartFile file,@RequestParam String SavePath)
            throws IllegalStateException {
        Map<String,String> resultMap = new HashMap<>();
        try{
            //获取文件后缀,因此此后端代码可接收一切文件,上传格式前端限定
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            // 重构文件名称
            System.out.println("前端传递的保存路径:"+SavePath);
            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
            String newVidoeName = pikId + "." + fileExt;
            System.out.println("重构文件名防止上传同名文件:"+newVidoeName);
            //保存视频
            File fileSave = new File(SavePath, newVidoeName);
            file.transferTo(fileSave);
            //构造Map将视频信息返回给前端
            //视频名称重构后的名称
            resultMap.put("newVidoeName",newVidoeName);
            //正确保存视频则设置返回码为200
            resultMap.put("resCode","200");
            //返回视频保存路径
            resultMap.put("VideoUrl",SavePath + "/" + newVidoeName);
            return  resultMap;

        }catch (Exception e){
            e.printStackTrace();
            e.getMessage();
            //保存视频错误则设置返回码为400
            resultMap.put("resCode","400");
            return  resultMap ;

        }
    }

如果你想限制上传大小,在spring boot主程序中添加下面的文件上传配置

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

@SpringBootApplication
public class WuwenjunApplication {

    public static void main(String[] args) {
        SpringApplication.run(WuwenjunApplication.class, args);
    }

    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize(DataSize.parse("400MB")); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("400MB"));
        return factory.createMultipartConfig();
    }

}

实现效果

视频上传前Vue前端

在这里插入图片描述

视频上传中Vue前端

在这里插入图片描述

视频上传成功后Vue前端

在这里插入图片描述前端收到后端返回值为
在这里插入图片描述

视频上传成功后Spring Boot后端

在这里插入图片描述

上传结果

在这里插入图片描述以上就是这期《Vue+Spring Boot使用ElementUI el-upload实现视频带参数上传(前后端代码详解)》的全部内容了。

  • 11
    点赞
  • 118
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
Vue 2中使用Element UI进行视频上传,你可以按照以下步骤进行操作: 1. 首先,在你的Vue项目中安装Element UI组件库。可以通过npm或yarn进行安装: ``` npm install element-ui --save ``` 2. 在项目的入口文件(通常是main.js)中,引入Element UI并注册相应的组件: ```javascript import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` 3. 在你需要使用上传视频的组件中,使用`<el-upload>`组件来实现文件上传功能。在组件的模板中添加如下代码: ```html <template> <el-upload action="your-upload-url" // 替换为你的上传接口地址 :on-success="handleSuccess" :before-upload="beforeUpload" :auto-upload="false" :file-list="fileList" accept="video/*" > <el-button slot="trigger" size="small" type="primary">选取视频文件</el-button> <div slot="tip" class="el-upload__tip">只能上传视频文件</div> </el-upload> </template> ``` 4. 在组件的script部分,定义相应的方法: ```javascript <script> export default { data() { return { fileList: [] // 用于存储选择的文件列表 } }, methods: { handleSuccess(response, file, fileList) { // 文件上传成功后的回调函数 console.log('上传成功') }, beforeUpload(file) { // 文件上传之前的钩子函数 // 可以在这里对文件进行一些验证,如文件大小、文件类型等 console.log('文件上传前') this.fileList.push(file) // 将选择的文件添加到fileList中 return false // 返回false表示不自动上传,需要手动触发上传 } } } </script> ``` 其中`handleSuccess`和`beforeUpload`分别是文件上传成功和上传前的回调函数,你可以根据需求进行相应的处理。 以上就是使用Vue 2和Element UI进行视频上传的基本步骤,你可以根据自己的需要进行进一步的扩展和优化。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值