Exemplo n.º 1
0
        public VideoFileModel Get(string videoFileName)
        {
            FileInfo       video     = null;
            VideoFileModel videoInfo = null;

            try
            {
                // Returns an instance of a video.
                using (ksalomon_listEntities db = new ksalomon_listEntities())
                {
                    video = (from v in db.FileInfoes where v.FileName.Trim() == videoFileName.Trim() select v).FirstOrDefault();
                    if (video != null)
                    {
                        videoInfo = new VideoFileModel
                        {
                            FileName        = video.FileName,
                            FilePath        = video.FilePath,
                            FileDescription = video.FileDescription,
                            FileSize        = video.FileSize,
                            CreatedDate     = video.CreatedDate,
                            UserID          = video.MemberFK.ToString()
                        };
                    }
                }
            }
            catch
            {
                return(null);
            }

            return(videoInfo);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 视频文件上传
        /// </summary>
        /// <param name="host"></param>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task <VideoFileModel> ExecuteVideo(string host, Stream stream, string fileName)
        {
            var response = new VideoFileModel();

            if (string.IsNullOrEmpty(host) || stream == null)
            {
                return(null);
            }

            using (var client = new HttpClient())
                using (var content = new MultipartFormDataContent())
                {
                    var fileContent = new StreamContent(stream);
                    fileContent.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                    fileContent.Headers.ContentDisposition          = new ContentDispositionHeaderValue("form-data");
                    fileContent.Headers.ContentDisposition.FileName = fileName;
                    content.Add(fileContent);

                    try
                    {
                        var result = await client.PostAsync(host, content);

                        if (result.StatusCode.ToString() != "OK")
                        {
                            return(null);
                        }

                        var json = await result.Content.ReadAsStringAsync();

                        var obj = JsonConvert.DeserializeObject <JObject>(json);
                        if (string.IsNullOrEmpty(obj?["Url"].ToString()))
                        {
                            return(null);
                        }

                        if (!string.IsNullOrEmpty(obj["Url"]?.ToString()))
                        {
                            response.Url = obj["Url"]?.ToString();
                        }
                        if (!string.IsNullOrEmpty(obj["Height"]?.ToString()))
                        {
                            response.Height = Convert.ToInt32(obj["Height"]?.ToString());
                        }
                        if (!string.IsNullOrEmpty(obj["Width"]?.ToString()))
                        {
                            response.Width = Convert.ToInt32(obj["Width"].ToString());
                        }
                        if (!string.IsNullOrEmpty(obj["PicUrl"]?.ToString()))
                        {
                            response.Thumb = obj["PicUrl"].ToString();
                        }

                        return(response);
                    }
                    catch
                    {
                        return(null);
                    }
                }
        }
Exemplo n.º 3
0
        public bool Update(VideoFileModel video, int recordID)
        {
            FileInfo updateVideo = null;

            // Updates an existing video.
            try
            {
                using (ksalomon_listEntities db = new ksalomon_listEntities())
                {
                    updateVideo = (from v in db.FileInfoes where v.id == recordID select v).FirstOrDefault();
                    if (updateVideo != null)
                    {
                        updateVideo.FileName        = Utils.ParseFileName(video.FileName);
                        updateVideo.FilePath        = video.FilePath;
                        updateVideo.FileDescription = video.FileDescription.Trim();
                        updateVideo.FileSize        = video.FileSize;
                        updateVideo.UpdatedDate     = DateTime.Now;

                        db.SaveChanges();
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 4
0
        public ActionResult Delete(VideoFileModel videoToDelete)
        {
            if (this._repository.Delete(videoToDelete.id))
            {
                return(RedirectToAction("Index"));
            }

            return(View());
        }
Exemplo n.º 5
0
        public ActionResult Index(HttpPostedFileBase file)
        {
            VideoFileModel videoToCreate = null;
            string         userID        = string.Empty;
            string         fileName      = string.Empty;

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    using (AmazonS3Client s3Client = new AmazonS3Client(_awsAccessKey, _awsSecretKey))
                    {
                        var request = new PutObjectRequest()
                        {
                            BucketName  = _bucketName,
                            CannedACL   = S3CannedACL.PublicRead, //PERMISSION TO FILE PUBLIC ACCESIBLE
                            Key         = file.FileName,
                            InputStream = file.InputStream,       //SEND THE FILE STREAM
                            ContentType = "video/mp4"
                        };

                        s3Client.PutObject(request);
                    }
                }
                catch (Exception ex) //ToDo
                {
                }

                //Get the UserID from Cookie
                if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("UserID"))
                {
                    userID = this.ControllerContext.HttpContext.Request.Cookies["UserID"].Value;
                } //ToDo add error checking

                videoToCreate                 = new VideoFileModel();
                videoToCreate.FileName        = file.FileName;
                videoToCreate.FileDescription = "Video Uploaded To Acme";
                videoToCreate.FilePath        = "https://s3-us-west-2.amazonaws.com/videokeith/" + fileName;
                videoToCreate.FileSize        = file.ContentLength.ToString();
                videoToCreate.UserID          = userID;
            }

            UploadPageModel upm = this._repository.Create(videoToCreate);

            ViewBag.VideoFiles = this._repository.GetAll(Utils.ConvertToInt(userID));

            if (upm.SuccessfulTransfer)
            {
                //Send out Email
                Utilities.Utils.SendOutEmail(fileName, "*****@*****.**");
                return(View("Index", upm));
            }

            return(RedirectToAction("Index")); //ToDo
        }
Exemplo n.º 6
0
        //[ValidateAntiForgeryToken]
        public int UploadVideo([FromForm] VideoFileModel filemodel, [FromQuery] string opration)
        {
            try
            {
                int slicenum = FileHelper.UploadVideo(filemodel);
                return(slicenum);

                //return RedirectToAction(nameof(Index));
            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
                return(-1);
            }
        }
Exemplo n.º 7
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string fileName = context.Request["fileName"];
            string fileExt  = context.Request["ext"];

            using (FileStream fileStream = File.OpenRead("d:/" + fileName + fileExt))
            {
                VideoFileModel videoFileModel = new VideoFileModel()
                {
                    VideoFileExt  = fileExt,
                    VideoFileName = fileName
                };
                RedisHelper.EnQueue("VideoFileInfo", SerializeHelper.SerializeToString(videoFileModel));
            }
        }
Exemplo n.º 8
0
 private static void StartConvert()
 {
     while (true)
     {
         int count = Common.RedisHelper.GetEqueueCount("videFileInfo");
         if (count > 0)
         {
             string         str       = Common.RedisHelper.Dequeue("videoFileInfo"); //出队
             VideoFileModel videoFile = Common.SerializeHelper.DeserializeToObject <VideoFileModel>(str);
             ConvertToVideo(videoFile);
         }
         else
         {
             Thread.Sleep(3000);
         }
     }
 }
Exemplo n.º 9
0
 private static void StartConvert()
 {
     while (true)
     {
         int count = Common.RedisHelper.GetQueueCount("videoFileInfo");
         if (count > 0)
         {
             //从队列中获取要进行视频转换的视频的信息
             string         str       = Common.RedisHelper.DeQueue("videoFileInfo");//出队.
             VideoFileModel videoFile = Common.SerializeHelper.DeSerializeToObj <VideoFileModel>(str);
             ConvertToVideo(videoFile);
         }
         else
         {
             Thread.Sleep(3000);
         }
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// 找到视频文件,并且进行转换
        /// </summary>
        /// <param name="videoFile"></param>
        private static void ConvertToVideo(VideoFileModel videoFile)
        {
            try
            {
                string  srcFileName = @"d:\" + videoFile.VideoFileName + videoFile.videoFileExt; //视频存在转码服务器的D盘中。
                string  destFile    = @"d:\" + videoFile.VideoFileName + ".flv";                 //全部转换为Flv格式
                string  destImgFile = @"d:\" + videoFile.VideoFileName + ".jpg";
                Process p           = new Process();
                //设置进程启动信息属性StartInfo,这是ProcessStartInfo类,包括了一些属性和方法:
                p.StartInfo.FileName        = @"D:\传智讲课\0718就业班\OA\第十三天\资料\\ffmpeg.exe"; //程序名
                p.StartInfo.UseShellExecute = false;
                //-y选项的意思是当输出文件存在的时候自动覆盖输出文件,不提示“y/n”这样才能自动化
                p.StartInfo.Arguments = "-i " + srcFileName + " -y -ab 56 -ar 22050 -b 800 -r 29.97 -s 420x340 " + destFile;    //执行参数
                                                                                                                                //  p.StartInfo.Arguments = "-i " + srcFileName + " -y -f image2  -ss 53 -t 0.001 -s  600x500 " + destImgFile;
                p.StartInfo.RedirectStandardInput  = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError  = true;//把外部程序错误输出写到StandardError流中
                p.ErrorDataReceived  += new DataReceivedEventHandler(p_ErrorDataReceived);
                p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
                p.Start();
                p.BeginErrorReadLine(); //开始异步读取
                p.WaitForExit();        //阻塞等待进程结束
                p.Close();              //关闭进程
                p.Dispose();            //释放资源
                CutPhotoImage(srcFileName, destImgFile);


                //将转换成功的flv视频回传给WEB服务器。
                WebClient webClient = new WebClient();
                webClient.UploadData("http://localhost:3872/VideoInfo/GetVideoFile?fileName=" + videoFile.VideoFileName + "&t=flv", System.IO.File.ReadAllBytes(destFile));

                //可以先判断图片文件是否存在,如果不存在返回的默认的图片。
                webClient.UploadData("http://localhost:3872/VideoInfo/GetVideoFile?fileName=" + videoFile.VideoFileName + "&t=jpg", System.IO.File.ReadAllBytes(destImgFile));

                //将原视频与目标视频删除。

                System.IO.File.Delete(srcFileName);
                System.IO.File.Delete(destFile);
                System.IO.File.Delete(destImgFile);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 11
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string fileName = context.Request["fileName"]; //文件路径
            string fileExt  = context.Request["ext"];      //文件扩展名

            //将传递过来的视频文件接收并且存到视频转换服务器的磁盘上,同时将视频的信息写到队列中
            using (FileStream fileStream = File.OpenWrite("D:/" + fileName + fileExt))
            {
                //将web服务器传递过来的视频保存到转换服务器磁盘上
                context.Request.InputStream.CopyTo(fileStream);
                //将视频信息写到队列中
                VideoFileModel videoFileModel = new VideoFileModel();
                videoFileModel.VideoFileName = fileName;
                videoFileModel.videoFileExt  = fileExt;
                string str = Common.SerializeHelper.SerializeToString(videoFileModel);
                Common.RedisHelper.Enqueue("videoFileInfo", str);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 执行视频 上传
        /// </summary>
        /// <param name="host"></param>
        /// <param name="file"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task <VideoFileModel> ExecuteVideo(string host, string file, string fileName = "")
        {
            var resp = new VideoFileModel();

            if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(file))
            {
                return(null);
            }

            var fileInfo = new FileInfo(file);

            using (var fs = fileInfo.OpenRead())
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = fileInfo.Name;
                }
                return(await ExecuteVideo(host, fs, fileName));
            }
        }
Exemplo n.º 13
0
        public List <VideoFileModel> GetAll(int userID)
        {
            // Returns a list with all videos for a userID.
            List <VideoFileModel> videoModels = new List <VideoFileModel>();

            try
            {
                using (ksalomon_listEntities db = new ksalomon_listEntities())
                {
                    List <FileInfo> videos = (from v in db.FileInfoes where v.MemberFK == userID select v).OrderByDescending(v => v.id).ToList();

                    //ToDo use data mapper
                    foreach (FileInfo record in videos)
                    {
                        VideoFileModel videoInfo = new VideoFileModel
                        {
                            FileName        = record.FileName,
                            FilePath        = record.FilePath,
                            FileDescription = record.FileDescription,
                            FileSize        = record.FileSize,
                            CreatedDate     = record.CreatedDate,
                            UpdatedDate     = record.UpdatedDate,
                            UserID          = record.MemberFK.ToString()
                        };

                        videoModels.Add(videoInfo);
                    }
                }
            }
            catch
            {
                return(null);
            }

            return(videoModels);
        }
Exemplo n.º 14
0
        public UploadPageModel Create(VideoFileModel video)
        {
            int videoExistsID = 0;

            //ToDo use DI
            UploadPageModel upm        = new UploadPageModel();
            string          outMessage = string.Empty;

            //populate ViewModel common values
            upm.FileName        = Utils.ParseFileName(video.FileName);
            upm.FileDescription = video.FileDescription.Trim();

            //Check to see if Video exists, Upsert if so
            videoExistsID = Exists(video.FileName.Trim());
            if (videoExistsID != 0)
            {
                if (!Update(video, videoExistsID))
                {
                    upm.SuccessfulTransfer = false;
                    upm.UploadErrors       = "Update Failed!";
                    return(upm);
                }
                else
                {
                    //Populate ViewModel status and errors
                    upm.SuccessfulTransfer = true;
                    upm.UploadErrors       = outMessage;
                    return(upm);
                }
            }

            // Creates a new video.
            using (ksalomon_listEntities db = new ksalomon_listEntities())
            {
                FileInfo videoInfo = new FileInfo
                {
                    FileName        = Utils.ParseFileName(video.FileName),
                    FilePath        = video.FilePath,
                    FileDescription = video.FileDescription.Trim(),
                    FileSize        = video.FileSize,
                    MemberFK        = Utils.ConvertToInt(video.UserID),
                    CreatedDate     = DateTime.Now
                };

                // Add the new object to the Members collection.
                db.FileInfoes.Add(videoInfo);

                // Save the change to the database.
                try
                {
                    db.SaveChanges();
                    //Populate ViewModel status and errors
                    upm.SuccessfulTransfer = true;
                    upm.UploadErrors       = outMessage;
                }
                catch (DbEntityValidationException e) //Capture Entity level errors
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        outMessage += string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            outMessage += string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                        ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    //Populate ViewModel status and errors
                    upm.SuccessfulTransfer = false;
                    upm.UploadErrors       = outMessage;
                    return(upm);
                }
                catch (Exception ex)                   //Capture generic errors
                {
                    //Populate ViewModel status and errors
                    upm.SuccessfulTransfer = false;
                    upm.UploadErrors       = ex.ToString();
                    return(upm);
                }
            }

            return(upm);
        }
Exemplo n.º 15
0
        public static int UploadVideo(VideoFileModel videoFile)
        {
            //前端传输是否为切割文件最后一个小文件
            var isLast = videoFile.isLast;
            //前端传输当前为第几次切割小文件
            var count = videoFile.Count;
            //获取前端处理过的传输文件名
            string fileName = videoFile.Name;

            //存储接受到的切割文件
            if (videoFile.Files.Length <= 0)
            {
                return(-1);
            }

            IFormFile formFile = videoFile.Files;

            //处理文件名称(去除.part*,还原真实文件名称)
            string newFileName = fileName.Substring(0, fileName.LastIndexOf('.'));

            //临时存储文件夹路径
            string desPath = Directory.GetCurrentDirectory() + @"/uploads/slice/" + newFileName;

            //判断指定目录是否存在临时存储文件夹,没有就创建
            if (!System.IO.Directory.Exists(desPath))
            {
                //不存在就创建目录
                System.IO.Directory.CreateDirectory(desPath);
            }

            //存储文件
            using (var stream = new FileStream(desPath + "/" + fileName, FileMode.Create))
            {
                formFile.CopyTo(stream);
            }
            //file.SaveAs("E:\\uploads\\slice\\" + newFileName + "\\" + fileName);


            //判断是否为最后一次切割文件传输
            if (isLast == "true")
            {
                //判断组合的文件是否存在
                finalpath = Directory.GetCurrentDirectory() + @"/uploads/" + 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(desPath);
                //将文件进行排序拼接
                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 bool Create(VideoFileModel video)
 {
     return(true);
 }
 public bool Update(VideoFileModel video, int recordID)
 {
     return(true);
 }