1. 自己项目学习中要用到上传视频功能,博主也遇到很多问题,查询了很多资料才将就着写完了部份代码,后续持续更新。。。。。新手写csdn可能不太好看。。体谅一下
2. 开始我的代码表演!
1.前端页面代码如下:
图片和视频的上传我都是设置了不立即上传,当点击添加视频信息的时候才和表单数据一起上传到后台操作。

 <div style="height: 130px;width:100%;border:1px solid rgba(56,166,255,.1);box-shadow: 0 0 8px #ccc;background-color: white;margin-top: -10px">
     <el-form :model="ruleForm"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
         <div class="demo-input-suffix" style="margin-top: 20px;float: left;padding-left: 10px;">
             <el-span style="font-size: 18px">名称:</el-span>
             <el-input style="width: 130px;"
                       placeholder="请输入视频名称"
                       v-model="ruleForm.name" @keyup.enter.native="onEnterSearch">
                 <i slot="prefix" class="el-input__icon el-icon-search"></i>
             </el-input>
             <el-span style="font-size: 18px;margin-left: 15px;">类别:</el-span>
             <el-select v-model="ruleForm.type" placeholder="请选择类别" style="width: 130px;" >
                 <el-option
                         v-for="item in options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                 </el-option>
             </el-select>
             <el-span style="font-size: 18px;margin-left: 15px;"> 状态:</el-span>
             <el-select v-model="ruleForm.status" placeholder="请选择状态" style="width: 130px;">
                 <el-option
                         v-for="item in status"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                 </el-option>
             </el-select>
             <el-span style="font-size: 18px;margin-left: 15px;"> 开始日期:</el-span>
             <el-date-picker
                     v-model="ruleForm.startTime"
                     type="date"
                     placeholder="选择日期" style="width: 135px;">
             </el-date-picker>
             <el-span style="font-size: 18px;margin-left: 15px;"> 结束日期:</el-span>
             <el-date-picker
                     v-model="ruleForm.endTime"
                     type="date"
                     placeholder="选择日期" style="width: 135px;">
             </el-date-picker>
         </div>
         <div class="demo-input-suffix" style="margin-top: 20px;float: left;padding-left: 400px;">
             <el-button type="primary" icon="el-icon-search" @click="submitForm('ruleForm')">查询</el-button>
             <el-button icon="el-icon-search" @click="resetForm('ruleForm')">重置</el-button>
             <el-button type="primary" @click="spxzVisible = true;return" >添加视频</el-button>
         </div>
     </el-form>
     <el-dialog
             title="添加视频"
             :visible.sync="spxzVisible"
             v-loading="loading"
             element-loading-text="拼命上传中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)"
             >
         <el-form ref="formData" :model="formData" :rules="rules" enctype="multipart/form-data">
             <el-form-item label="视频名称" label-width="80px" style="width: 300px" prop="videoName">
                 <el-input v-model="formData.videoName"></el-input>
             </el-form-item>
             <el-form-item label="视频封面" label-width="80px" class="upload-img" prop="file">
                 <!--:style="{backgroundImage:'url(' + dialogImageUrl + ')', backgroundRepeat:'no-repeat', backgroundPosition:'center center', backgroundSize: 'contain'}"-->
                 <el-upload
                         action="#"
                         ref="uploadImg"
                         :before-upload="beforeupload"
                         :show-file-list="false"
                         :on-change="handlePictureCardPreview"
                         accept="image/png,image/gif,image/jpg,image/jpeg"
                         list-type="picture-card"
                         :limit="1"
                         :on-exceed="handleExceed"
                         style="margin-right: 390px"
                         >
                     <i v-show="!dialogImageUrl" class="el-icon-plus"></i>
                     <img v-if="imageUrl" :src="imageUrl" class="avatar">
                 </el-upload>
                 <!--查看大图-->
                 <el-dialog :visible.sync="dialogVisible">
                     <img width="100%" :src="dialogImageUrl" alt="">
                 </el-dialog>
             </el-form-item>
             <el-form-item label="视频上传" prop="video" label-width="80px" style="position: absolute;top: 145px;left: 320px;">
                 <el-upload
                         class="el-upload-text"
                         action="#"
                         :on-preview="handlePreview"
                         :before-remove="beforeRemove"
                         :limit="1"
                         :on-exceed="handleExceed"
                         accept="video/mp4, video/ogg, video/flv,video/avi,video/wmv,video/rmvb"
                         :show-file-list = "showFileFlag"
                         :file-list="fileList"
                         :on-change = "loadVideo"
                         :auto-upload="false">
                     <el-button size="small" type="primary">点击上传</el-button>
                 </el-upload>
             </el-form-item>
             <el-form-item label="类别" label-width="80px" prop="videoType" style="width: 300px;position: absolute;top: 84px;left: 320px;">
                 <el-select v-model="formData.videoType" placeholder="请选择">
                     <el-option
                             v-for="item in options"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                     </el-option>
                 </el-select>
             </el-form-item>
             <el-form-item label="视频时长" prop="videoTimes" label-width="80px"  style="width: 300px">
                 <el-input v-model="formData.videoTimes"></el-input>
             </el-form-item>
             <el-form-item label="状态" prop="videoStatus" label-width="80px"  style="width: 300px; position: absolute;top: 317px;left: 320px;">
                 <el-tooltip :content="'视频状态: ' + formData.videoStatus" placement="top">
                     <el-switch v-model="formData.videoStatus"  active-color="#13ce66"
                                inactive-color="#ff4949" active-value="启用"
                                inactive-value="禁用" style="margin-right: 300px;"></el-switch>
                 </el-tooltip>
             </el-form-item>
             <el-form-item label="视频介绍" prop="videoJj" label-width="80px">
                 <el-input type="textarea" v-model="formData.videoJj"></el-input>
             </el-form-item>
             <el-form-item>
                 <el-button type="primary" @click="onSubmit('formData')" >立即添加</el-button>
                 <el-button @click="spxzVisible = false">取消</el-button>
             </el-form-item>
         </el-form>
     </el-dialog>
 </div>


部分css代码
 .el-upload--picture-card {
            background-color: transparent;
        }
        .avatar-uploader {
            border: 1px dashed #c0ccda;
            border-radius: 6px;
            box-sizing: border-box;
            width: 148px;
            height: 148px;
            line-height: 146px;
            vertical-align: top;
        }
        .el-progress-circle{
            margin-top:-20px;
        }
        .el-dialog__header{
            background-color: #409EFF;
        }
      .el-dialog__close{
            color:white !important;
        }
        .avatar {
            width: 148px;
            height: 148px;
            display: block;
        }

2 js代码如下:

		//显示弹框
        spxzVisible: false,
        //图片地址
        imageUrl: '',
        formData:{//添加视频弹出框表单信息
            videoName:'',
            videoType:'',
            videoTimes:'',
            videoJj:'',
            videoStatus:'启用',
            file:'',
            video:''
        },
        dialogImageUrl: '', // 图片
        loading:false,
        videoFlag:false,
        formObj:new FormData(),
        //验证表单
        rules:{
            videoName:[{required: true, message: '必填项', trigger: 'blur'}],
            file:[{required: true, message: '请上传图片' }],
            video:[{required: true, message: '请上传视频' }],
            videoType:[{required: true, message: '必填项',trigger: ['blur', 'change'] }],
            videoTimes:[{required: true, message: '必填项',trigger: ['blur', 'change'] }],
            // videoStatus:[{required: true, message: '必填项',trigger: ['blur', 'change'] }],
            videoJj:[{required: true, message: '必填项',trigger: ['blur', 'change'] }]
        }




	methods:{
        // 阻止upload的自己上传,进行再操作
        beforeupload (file) {
            var vm = this;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }

            return false
        },
        // 图片预览
        handlePictureCardPreview (file) {
            var vm = this;
            vm.formData.file=file.raw;
            vm.imageUrl = URL.createObjectURL(file.raw);
            vm.dialogImageUrl = file.url
        },




        //点击上传的video
        handlePreview(file) {
            console.log(file);
        },
        loadVideo:function(file,fileList){
            vm.formData.video = file.raw;
        },
        //上传限制
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
        },
        //移除资源前访问
        beforeRemove(file, fileList) {
            if(['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1&& file.size / 1024 / 1024  > 100){
                return this.$confirm(`确定移除 ${ file.name }?`);
            }
        },
        //查询数据
        submitForm(formName) {
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //重置查询按钮
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //点击立即添加按钮
        onSubmit:function (formName) {
            var vm = this;
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    if(vm.formData.video){
                    	//验证视频大小和格式
                        const isLt100M = vm.formData.video.size / 1024 / 1024  < 100;
                        if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(vm.formData.video.type) == -1) {
                            vm.$message.error('请上传正确的视频格式');
                            vm.showFileFlag = false;
                            return false;
                        }
                        if (!isLt100M) {
                            vm.$message.error('上传视频大小不能超过100MB哦!');
                            vm.showFileFlag = false;
                            return false;
                        }
                    }
                    vm.loading = true;
                    //封装表单数据传到后台
                    vm.formObj.append("videoName",vm.formData.videoName);
                    vm.formObj.append("videoType",vm.formData.videoType);
                    vm.formObj.append("videoTimes",vm.formData.videoTimes);
                    vm.formObj.append("videoJj",vm.formData.videoJj);
                    vm.formObj.append("videoStatus",vm.formData.videoStatus);
                    vm.formObj.append("file",vm.formData.video);
                    vm.formObj.append("file",vm.formData.file);
                    console.log(vm.formObj)
                    $.ajax({
                        url: '/file/upload',
                        data: vm.formObj,
                        type: 'POST',
                        dataType: 'json',
                        cache: false,
                        processData: false,
                        contentType: false,
                        success: function (data) {
                            vm.loading = false;
                        },
                        error:function () {
                            vm.loading = false;
                            vm.$message.error("添加失败!!")
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }

3.后台接收ajax传递的数据,后面保存在mongodb详细代码还没写完,这里先展示接收收据的代码。。

/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@ApiOperation(value = "上传文件测试", notes = "上传文件测试")
	@PostMapping(value="/upload",produces = "application/json")
	@ResponseBody
	public ResultForm uploadFile(@RequestParam("videoName")String videoName,@RequestParam("videoType")String videoType,@RequestParam("videoTimes")String videoTimes,
								 @RequestParam("videoJj")String videoJj,@RequestParam("videoStatus")String videoStatus,@RequestParam("file") MultipartFile[] file) throws IOException, ServletException {
		// 获得提交的文件名
		String fileName = file[0].getOriginalFilename();
		// 获取文件输入流
		InputStream ins = file[0].getInputStream();
		// 获取文件类型
		String contentType = file[0].getContentType();
		// 将文件存储到mongodb中
		ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
		logger.info("保存成功,objectId:" + objectId);
		return new ResultForm(true,"上传成功");
	}

4.由于使用的是springboot内置的tomcat,所以上传文件大小超过1M页面都会报错,所以必须修改内置tomcat的限制,只需在配置文件修改即可,代码如下

#设置springboot的内置tomcat上传文件大小
#配置文件传输
spring.servlet.multipart.enabled =true  
spring.servlet.multipart.file-size-threshold =0
#单个数据的大小
spring.servlet.multipart.max-file-size = 100MB
#总数据的大小
spring.servlet.multipart.max-request-size=100MB

修改完后就可以上传视频文件了!!!!!
5.最后贴出代码运行截图。。。个人项目希望各位大佬多多给小弟提建议
在这里插入图片描述点击添加视频按钮后上传视频信息
在这里插入图片描述点击理解添加后
在这里插入图片描述
在这里插入图片描述后台获取到图片和视频信息。。。。。后续代码还在开发中,

  • 完整的逻辑就是存储到oss或者mongodb或者ftp中,,,博主会三个都写,待开发
    上传成功后可在页面显示图片以及播放视频。。
  • 有任何问题可联系博主微信15779500118,,,菜鸟一枚。
Logo

前往低代码交流专区

更多推荐