AWS лямбда-функция и s3 в Asp NetCore - PullRequest
2 голосов
/ 03 февраля 2020

Я новичок в AWS и Asp NetCore. Помогите мне найти решение. Я использую Asp NetCore, как мне использовать лямбда-функцию для загрузки отсеченного файла в s3? У меня есть IFormFile, но я хочу использовать URL-адрес s3 вместо IFormFile и загрузить его в корзину s3. Я использовал библиотеку ffmpeg, чтобы вырезать видео, и я хочу отправить URL-адрес s3 с помощью лямбда-функции и снова загрузить вывод обрезанного видеофайла в каталог ведра s3, который я создал в консоли s3.

using Abp.UI;
using FFmpeg.NET;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using Amazon.S3;
using System.Threading.Tasks;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using IdentityModel.Client;
using Amazon;
using System.Net.Http;

namespace VideoSlicer.About
{
    public class AboutAppService : IAboutAppService
    {

        //Assigning readonly IHostingEnvironment
        private readonly IHostingEnvironment _appEnvironment;
        private readonly string bucketName = "videoslicerpuru";
        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.Region;
        /*
                private const string newFile = "QQ.mp4";
                private const string newFile1 = "637156754716419260QQ.mp4";
                private const string filePath = @"C:\Users\Purushottam\Downloads\VideoSlicer\5.1.1\aspnet-core\src\VideoSlicer.Web.Host\wwwroot\images\";*/


        private static IAmazonS3 client;

        //Making Constructor and passin IHostingEnvironment
        public AboutAppService(IHostingEnvironment appEnvironment)

        {
            _appEnvironment = appEnvironment;
        }


        //Function which upload video and slice video accordingly start time and finish time given by the user
        public async Task UploadImage(IFormFile file, string Start, string Finish)
        {

            HttpClient cli = new HttpClient();
            cli.DefaultRequestHeaders.ExpectContinue = false;



            try
            {
                //Taking out the extension of the file
                var convertedExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
                //Comparing the extension whether uploaded file is video or not
                if (convertedExtension != ".mp4" && convertedExtension != ".flv" && convertedExtension != ".3GP" && convertedExtension != ".OGG" && convertedExtension != ".AVI" && convertedExtension != ".WMV ")
                {
                    throw new UserFriendlyException("Please Select Valid Video file to clip!!");
                }
                //Checking if the file is null or has not been selected any file
                if (file == null || file.Length == 0)
                {
                    throw new UserFriendlyException("Please Select any file.");
                }
                //declaring web root path
                string path_Root = _appEnvironment.WebRootPath;

                //setting path root and saving video to the given path
                string pathOfVideo = path_Root + "\\video\\";
                string path_to_Video = path_Root + "\\images\\" + file.FileName;

                using (var stream = new FileStream(path_to_Video, FileMode.Create))

                {
                    await file.CopyToAsync(stream);

                }



                client = new AmazonS3Client("AccessKey", "SecretKey", bucketRegion);
                TransferUtility utility = new TransferUtility(client);
                TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();



                string nameOfFile = file.FileName.ToString();
                string videoPath = path_to_Video.ToString();
                await utility.UploadAsync(videoPath, bucketName, nameOfFile);
                Console.WriteLine("Upload 2 completed");


                //To cut video, using ffmpeg media file where the video is saved
                var input = new MediaFile(path_to_Video);
                //The output of the clipped video and saving in a different folder

                string nameFile = DateTime.Now.Ticks + file.FileName;
                string nameBucket = bucketName + "/videoslice/";
                var output = new MediaFile(path_Root + "/video/" + nameFile);
                client = new AmazonS3Client(bucketRegion);
                //making the object of Engine using ffmpeg application file
                var ffmpeg = new Engine("C:\\ffmpeg\\bin\\ffmpeg.exe");
                //making object of Conversion Option of ffmpeg
                var options = new ConversionOptions();
                //Converting string to double
                var startTime = Convert.ToDouble($"{Start}");
                var finishTime = Convert.ToDouble($"{Finish}");
                //clipping video by given user input
                options.CutMedia(TimeSpan.FromSeconds(startTime), TimeSpan.FromSeconds(finishTime - startTime));
                await ffmpeg.ConvertAsync(input, output, options);


                string clipPath = path_Root + "\\video\\" + nameFile;

                //Checking if start time is greater then finish time
                if (startTime > finishTime)
                {
                    throw new UserFriendlyException("Please Enter Valid Second to proceed");
                }
                //Checking if start time is equal to finish time
                if (startTime == finishTime)
                {
                    throw new UserFriendlyException("Please Enter Valid Second to proceed");
                }

                var a =  utility.UploadAsync(clipPath, nameBucket, nameFile);
                Console.WriteLine("Upload 2 completed");



            }
            catch (AmazonS3Exception e)
            {
                string err = e.Message;
                throw e;
            }
            catch (InternalBufferOverflowException a)
            {
                string me = a.Message;
                throw a;
            }
            catch (HttpRequestException c)
            {
                string error = c.Message;
                throw c;
            }
            catch (DriveNotFoundException e)
            {
                string mes = e.Message;
                throw e;
            }
            catch(NullReferenceException e)
            {
                throw new UserFriendlyException (500, "Please Select a file to proceed",e.Message);
            }

        }
    }
}
...