天天看點

springboot+vue+elementui添加視訊和圖檔

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.最後貼出代碼運作截圖。。。個人項目希望各位大佬多多給小弟提建議

springboot+vue+elementui添加視訊和圖檔

點選添加視訊按鈕後上傳視訊資訊

springboot+vue+elementui添加視訊和圖檔

點選了解添加後

springboot+vue+elementui添加視訊和圖檔
springboot+vue+elementui添加視訊和圖檔

背景擷取到圖檔和視訊資訊。。。。。後續代碼還在開發中,

  • 完整的邏輯就是存儲到oss或者mongodb或者ftp中,,,部落客會三個都寫,待開發

    上傳成功後可在頁面顯示圖檔以及播放視訊。。

  • 有任何問題可聯系部落客微信15779500118,,,菜鳥一枚。