NET实现分片上传视频,截取

UpLoadBigFile.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpLoadBigFile.aspx.cs" Inherits="Pro.UpLoadBigFile" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
</head>
<body>
<!--上传视频-->
<div>
    <div>
        <div>
            <div>
                <span class="">上传视频</span>
            </div>
            <input id="uploadvideofile" type="file" accept="video/mp4,video/quicktime" class="up-video"/>
        </div>
    </div>
    <div id="videoplayer" style="display: none"></div>
    <div id="videooutput"></div>
    <div>
        <p style="color: #797979; margin-top: 5px; font-size: 12px;">视频格式必须为: mp4或mov。视频时长须在15秒以内,超出时长系统将自动截取前15秒内容。</p>
    </div>
</div>

<script src="Scripts/ajax.1.5.2.js"></script>
<%--传视频相关--%>
<script type="text/javascript">
    $('#uploadvideofile').change(function() {
        var file, videoURL, windowURL;
        var filemaxsize = 1024 * 1024 * 20; //200M 
        if (fileValid(this, filemaxsize, 'video')) {
            file = this.files[0];
            try {
                var temp = ajax.upload_big(
                    "AjaxHandlers/UploadVideoHandler.ashx?opration=uploadv", //文件上传地址
                    "#uploadvideofile", //input = file 选择器
                    1024 * 1024, //切割文件大小
                    "*", //文件限制类型 mime类型
                    function(index) { //上传成功事件
                        //console.log("slice [ " + index + "] uploaded")
                    },
                    function(index, length) { //上传进度事件
                        //console.log(index + "/" + length);
                        //var ratio = (index / length) * 100.00 | 0.00;
                        //var progress = $(".progress > div");
                        //progress.css("width", ratio + "%");
                        //progress.attr("aria-valuenow", index);
                        //progress.attr("aria-valuemax", length);
                        //progress.children("span").text("" + ratio + "%");
                    },
                    function(index, length) { //超时处理事件
                        console.log(index + "/" + length);
                    }
                );
            } catch (e) {
                console.log(e.name + " " + e.message);
            }
            videoURL = null;
            windowURL = window.URL || window.webkitURL;
            videoURL = windowURL.createObjectURL(file);
            $('#videoplayer').html('<video src="' + videoURL + '" controls="controls"></video>');
            setTimeout(function() { createIMG(); }, 800);
        }
    });

    //验证上传文件大小和类型
    /**
     * 
     * @param {this} value_ [获取input对象,一般为this]
     * @param {[number]} size_ [文件限制的大小,单位为kb]
     * @param {[string]} type_ [文件类别]
     * @param {[function]} callback [验证通过的回调]
     */
    function fileValid(value_, size_, type_, callback) {
        var file = value_.files[0];
        var fileSize = (file.size / 1024).toFixed(0); //文件大小
        var fileType = value_.value.substring(value_.value.lastIndexOf(".")); //文件类型

        if (fileSize > size_) {
            alert('视频过大,请选择小于200MB的视频!');
            return false;
        }
        switch (type_) {
        case 'video':
            if (!fileType.match(/.mp4|.mov/i)) {
                alert('请上传正确格式的视频!');
                return false;
            }
            break;
        default:
            alert('参数设置不正确!');
            return false;
            break;
        }
        return true;
    }

    var createIMG = function() {
        var scale = 0.25,
            video = $('#videoplayer').find('video')[0],
            canvas = document.createElement("canvas"),
            canvasFill = canvas.getContext('2d');
        canvas.width = video.videoWidth * scale;
        canvas.height = video.videoHeight * scale;
        canvasFill.drawImage(video, 0, 0, canvas.width, canvas.height);
        var src = canvas.toDataURL("image/jpeg");
        $('#videooutput').html('<img id="imgSmallView" src="' + src + '" alt="预览图" />');
    }
</script>

<script>
    (function() {
        //$("#uploadvideofile").change(function () {
        //    var temp = ajax.upload_big(
        //        "AjaxHandlers/UploadVideoHandler.ashx", //文件上传地址
        //        "#uploadvideofile", //input = file 选择器
        //        1024 * 1024, //切割文件大小
        //        "*", //文件限制类型 mime类型
        //        function(index) { //上传成功事件
        //            //console.log("slice [ " + index + "] uploaded")
        //        },
        //        function(index, length) { //上传进度事件
        //            //console.log(index + "/" + length);
        //            //var ratio = (index / length) * 100.00 | 0.00;
        //            //var progress = $(".progress > div");
        //            //progress.css("width", ratio + "%");
        //            //progress.attr("aria-valuenow", index);
        //            //progress.attr("aria-valuemax", length);
        //            //progress.children("span").text("" + ratio + "%");
        //        },
        //        function(index, length) { //超时处理事件
        //            console.log(index + "/" + length);
        //        }
        //    );
        //    console.log(temp);
        //});
    })();
</script>
</body>
</html>

UploadVideoHandler.ashx

<%@ WebHandler Language="C#" Class="UploadVideoHandler" %>

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using VideoEncoder;

public class UploadVideoHandler : IHttpHandler
{
    private string opration
    {
        get { return HttpContext.Current.Request["opration"] ?? ""; }
    }

    public void ProcessRequest(HttpContext context)
    {
        switch (opration)
        {
            case "uploadv":
                int slicenum = UploadVedio();
                context.Response.Write(slicenum);
                break;
            //case "":
            //    break;
            default:
                context.Response.Write("无效参数");
                break;
        }
    }

    private string finalpath = "";

    public int UploadVedio()
    {
        //前端传输是否为切割文件最后一个小文件
        var isLast = HttpContext.Current.Request["isLast"];
        //前端传输当前为第几次切割小文件
        var count = HttpContext.Current.Request["count"];
        //获取前端处理过的传输文件名
        string fileName = HttpContext.Current.Request["name"];
        //存储接受到的切割文件
        if (HttpContext.Current.Request.Files.Count <= 0) return -1;
        HttpPostedFile file = HttpContext.Current.Request.Files[0];

        //处理文件名称(去除.part*,还原真实文件名称)
        string newFileName = fileName.Substring(0, fileName.LastIndexOf('.'));
        //判断指定目录是否存在临时存储文件夹,没有就创建
        if (!System.IO.Directory.Exists(@"E:\uploaded\slice\" + newFileName))
        {
            //不存在就创建目录 
            System.IO.Directory.CreateDirectory(@"E:\uploaded\slice\" + newFileName);
        }

        //存储文件
        file.SaveAs("E:\\uploaded\\slice\\" + newFileName + "\\" + HttpContext.Current.Request["name"]);
        //判断是否为最后一次切割文件传输
        if (isLast == "true")
        {
            //判断组合的文件是否存在
            finalpath = @"E:\\uploaded\\" + newFileName;
            if (File.Exists(finalpath)) //如果文件存在
            {
                File.Delete(finalpath); //先删除,否则新文件就不能创建
            }

            //创建空的文件流
            FileStream FileOut = new FileStream(finalpath, FileMode.CreateNew, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(FileOut);
            //获取临时存储目录下的所有切割文件
            string[] allFile = Directory.GetFiles("E:\\uploaded\\slice\\" + newFileName);
            //将文件进行排序拼接
            allFile = allFile.OrderBy(s => int.Parse(Regex.Match(s, @"\d+$").Value)).ToArray();
            for (int i = 0; i < allFile.Length; i++)
            {
                FileStream FileIn = new FileStream(allFile[i], FileMode.Open);
                BinaryReader br = new BinaryReader(FileIn);
                byte[] data = new byte[1048576]; //流读取,缓存空间
                int readLen = 0; //每次实际读取的字节大小
                readLen = br.Read(data, 0, data.Length);
                bw.Write(data, 0, readLen);
                //关闭输入流
                FileIn.Close();
            }

            //关闭二进制写入
            bw.Close();
            FileOut.Close();
            ClipVideo();
        }

        return int.Parse(count) + 1;
    }

    public void ClipVideo()
    {
        /**
         * 支持视频格式:mpeg,mpg,avi,dat,mkv,rmvb,rm,mov.
         *不支持:wmv
         * **/
        VideoEncoder.Encoder enc = new VideoEncoder.Encoder();
        //ffmpeg.exe的路径,控制台程序会在执行目录(....FFmpeg测试\bin\Debug)下找此文件,
        enc.FFmpegPath = "ffmpeg.exe";
        //视频路径
        string finalname = Path.GetFileNameWithoutExtension(finalpath);
        string videoFilePath = finalpath; //"d:\\01.avi";
        finalpath = finalpath.Replace(finalname, finalname + "15S");

        VideoFile videoFile = new VideoFile(videoFilePath);

        enc.GetVideoInfo(videoFile);

        TimeSpan totaotp = videoFile.Duration;
        string totalTime = string.Format("{0:00}:{1:00}:{2:00}", (int) totaotp.TotalHours, totaotp.Minutes,
            totaotp.Seconds);

        #region 自定义逻辑

        //string sourceFileName = Path.GetFileName(upFile.get_FileName()); //取出上传的视频的文件名,进而取出该文件的扩展名
        //string sourceFileName = "02.avi";
        //string flv_file = System.IO.Path.ChangeExtension("d:\\01.avi", ".flv");
        //string Command = " -i \"" + FromName + "\" -y -ab 32 -ar 22050 -b 800000 -s  480*360 \"" + ExportName + "\""; //Flv格式  

        //转换视频为flv
        //ffmpeg -i F:\01.wmv -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 f:\test.flv

        //视频截图,fileName视频地址,imgFile图片地址
        //ffmpeg -i input.flv -y -f image2 -ss 10.11 -t 0.001 -s 240x180 catchimg.jpg;
        //ImgstartInfo.Arguments = "   -i   " + fileName + "  -y  -f  image2   -ss 2 -vframes 1  -s   " + FlvImgSize + "   " + flv_img;

        //string Command = " -i \"test.wmv\" -y -ab 32 -ar 22050 -b 800000 -s 320*240 \"2.flv\"";
        //string Command = "E:\\FFmpeg\\ffmpeg.exe -i E:\\ClibDemo\\VideoPath\\admin\\a.wmv -y -ab 56 -ar 22050 -b 500 -r 15 -s 320*240 " ExportName;

        //3.重新编码进行剪切
        //ffmpeg -ss [start] -t [duration] -i [in].mp4  -c:v libx264 -c:a aac -strict experimental -b:a 98k [out].mp4
        //相对来说比较精确,可是还是不是特别精确

        //string Command =" -ss 00:00:00 -t 00:00:15 -i  d:\\01.avi   d:\\output.avi"; // ffmpeg -ss 00:00:10 -t 00:01:22 -i 五月天-突然好想你.mp3  out.mp3  
        string Command = " -ss 00:00:00 -t 00:00:15 -i  " + videoFilePath + "   E:\\output.avi";
        string Command1 =
            " -i d:\\01.avi -vf \"drawtext=fontfile=simhei.ttf: text='南通极客如皋张HC':x=w-tw-10:y=10:fontsize=28:fontcolor=red:shadowy=2\" d:\\output1.avi";
        string Command2 =
            " -i d:\\01.avi -vf \"drawtext=fontfile=simhei.ttf: text='南通极客QQ(827XXXXXX)':y=h-line_h-10:x=(w-mod(30*n\\,w+tw)):fontsize=34:fontcolor=yellow:shadowy=2\" d:\\output2.avi";

        System.Diagnostics.Process p = new System.Diagnostics.Process();
        //非控制台程序必须写完整路径
        p.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/" + enc.FFmpegPath + "");
        p.StartInfo.Arguments = Command;
        //p.StartInfo.Arguments = Command1;
        //Asp.net 获取当前目录
        p.StartInfo.WorkingDirectory =
            HttpContext.Current.Server
                .MapPath("~/bin"); //HttpContext.Current.Request.MapPath("~/"); //Environment.CurrentDirectory;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = false;
        //开始执行
        p.Start();
        p.BeginErrorReadLine();
        p.WaitForExit();
        p.Close();
        p.Dispose();

        #endregion

        Console.WriteLine("时间长度:{0}", totalTime);
        Console.WriteLine("高度:{0}", videoFile.Height);
        Console.WriteLine("宽度:{0}", videoFile.Width);
        Console.WriteLine("数据速率:{0}", videoFile.VideoBitRate);
        Console.WriteLine("数据格式:{0}", videoFile.VideoFormat);
        Console.WriteLine("比特率:{0}", videoFile.BitRate);
        Console.WriteLine("文件路径:{0}", videoFile.Path);
        Console.ReadKey();
    }


    public bool IsReusable
    {
        get { return false; }
    }
}

如图:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

下载

下载地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值