Vue+Element UI 實現視頻上傳功能

一、前言

項目中需要提供一個視頻介紹,使用戶能夠快速、方便的瞭解如何使用產品以及註意事項。

前臺使用Vue+Element UI中的el-upload組件實現視頻上傳及進度條展示,後臺提供視頻上傳API並返回URL。

二、具體實現

1、效果圖展示

2、HTML代碼

<div class="album albumvideo">
    <div>
        <p class="type_title">
            <span>視頻介紹</span>
        </p>
        <div class="pic_img">
            <div class="pic_img_box">
                <el-upload class="avatar-uploader"
                           action="上傳地址"
                           v-bind:data="{FoldPath:'上傳目錄',SecretKey:'安全驗證'}"
                           v-bind:on-progress="uploadVideoProcess"
                           v-bind:on-success="handleVideoSuccess"
                           v-bind:before-upload="beforeUploadVideo"
                           v-bind:show-file-list="false">
                    <video v-if="videoForm.showVideoPath !='' && !videoFlag"
                           v-bind:src="videoForm.showVideoPath"
                           class="avatar video-avatar"
                           controls="controls">
                        您的瀏覽器不支持視頻播放
                    </video>
                    <i v-else-if="videoForm.showVideoPath =='' && !videoFlag"
                       class="el-icon-plus avatar-uploader-icon"></i>
                    <el-progress v-if="videoFlag == true"
                                 type="circle"
                                 v-bind:percentage="videoUploadPercent"
                                 style="margin-top:7px;"></el-progress>
                </el-upload>
            </div>
        </div>
    </div>
    <p class="Upload_pictures">
        <span></span>
        <span>最多可以上傳1個視頻,建議大小50M,推薦格式mp4</span>
    </p>
</div>

JS代碼

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            videoFlag: false,
            //是否顯示進度條
            videoUploadPercent: "",
            //進度條的進度,
            isShowUploadVideo: false,
            //顯示上傳按鈕
            videoForm: {
                showVideoPath: ''
            }
        },
        methods: {
            //上傳前回調
            beforeUploadVideo(file) {
                var fileSize = file.size / 1024 / 1024 < 50;
                if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
                    layer.msg("請上傳正確的視頻格式");
                    return false;
                }
                if (!fileSize) {
                    layer.msg("視頻大小不能超過50MB");
                    return false;
                }
                this.isShowUploadVideo = false;
            },
            //進度條
            uploadVideoProcess(event, file, fileList) {
                this.videoFlag = true;
                this.videoUploadPercent = file.percentage.toFixed(0) * 1;
            },
            //上傳成功回調
            handleVideoSuccess(res, file) {
                this.isShowUploadVideo = true;
                this.videoFlag = false;
                this.videoUploadPercent = 0;
                
                //前臺上傳地址
                //if (file.status == 'success' ) {
                //    this.videoForm.showVideoPath = file.url;
                //} else {
                //     layer.msg("上傳失敗,請重新上傳");
                //}

                //後臺上傳地址
                if (res.Code == 0) {
                    this.videoForm.showVideoPath = res.Data;
                } else {
                    layer.msg(res.Message);
                }
            }
        }
    })
</script>

4.後臺代碼

/// <summary>
/// 上傳視頻
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult UploadVideo()
{
    try
    {
        var secretKey = HttpContext.Current.Request["SecretKey"];
        if (secretKey == null || !_secretKey.Equals(secretKey))
            return Ok(new Result(-1, "驗證身份失敗"));
        var files = HttpContext.Current.Request.Files;
        if (files == null || files.Count == 0)
            return Ok(new Result(-1, "請選擇視頻"));
        var file = files[0];
        if (file == null)
            return Ok(new Result(-1, "請選擇上傳的視頻"));
        //存儲的路徑             
        var foldPath = HttpContext.Current.Request["FoldPath"];
        if (foldPath == null)
            foldPath = "/Upload";
        foldPath = "/UploadFile" + "/" + foldPath;
        if (foldPath.Contains("../"))
            foldPath = foldPath.Replace("../", "");
        //校驗是否有該文件夾 
        var mapPath = AppDomain.CurrentDomain.BaseDirectory + foldPath;
        if (!Directory.Exists(mapPath))
            Directory.CreateDirectory(mapPath);
        //獲取文件名和文件擴展名
        var extension = Path.GetExtension(file.FileName);
        if (extension == null || !".ogg|.flv|.avi|.wmv|.rmvb|.mov|.mp4".Contains(extension.ToLower()))
            return Ok(new Result(-1, "格式錯誤"));

        string newFileName = Guid.NewGuid() + extension;
        string absolutePath = string.Format("{0}/{1}", foldPath, newFileName);
        file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + absolutePath);
       
        string fileUrl = string.Format("{0}://{1}{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Authority, absolutePath);
        return Json(new ResultData(0, "success",fileUrl));
    }
    catch (Exception e)
    {
        Logger.Error("UploadVideo is error", GetType(), e);
        return Json(new Result(-1, "上傳失敗"));
    }
}

三、總結

註意:Web.Config文件配置之限制上傳文件大小和時間的屬性配置(1KB=1024B1MB=1024KB1GB=1024MB)

在Web.Config文件中配置限制上傳文件大小與時間字符串時,是在<httpRuntime><httpRuntime/>節中完成的,需要設置以下2個屬性:

maxRequestLength屬性:該限制可用於防止因用戶將大量文件傳遞到該服務器而導致的拒絕服務攻擊。指定的大小以KB為單位,默認值為4096KB(4MB)。executionTimeout屬性:指定在ASP.NET應用程序自動關閉前,允許執行請求的最大秒數。單位為秒,默認值為110s。

到此這篇關於Vue+Element UI 實現視頻上傳功能的文章就介紹到這瞭,更多相關vue視頻上傳內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: