Ejemplo n.º 1
0
        public async Task <IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return(Content("file not selected"));
            }

            var path = Path.Combine(_storage, file.FileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            if (!System.IO.File.Exists(path))
            {
                throw new Exception();
            }

            var clientS3 = new AmazonS3Client(_awsAccessKeyS3, _awsSecretKeyS3, RegionEndpoint.USEast1);
            var fileInfo = new FileInfo(path);

            var putObjectRequest = new PutObjectRequest()
            {
                InputStream = fileInfo.OpenRead(),
                BucketName  = _bucketName,
                Key         = file.FileName
            };

            var response = await clientS3.PutObjectAsync(putObjectRequest);

            if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("S3 uploading failed");
            }

            string subject = "New file in S3 bucket";
            string body    = $"New file {file.FileName} has been uploaded to S3 bucket {_bucketName}";

            var clientSNS       = new AmazonSimpleNotificationServiceClient(_awsAccessKeySNS, _awsSecretKeySNS, RegionEndpoint.USEast1);
            var publishResponse = await clientSNS.PublishAsync(new PublishRequest(_topic, body, subject));

            if (publishResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("SNS publishishing falied");
            }

            Entities.File filedb = new Entities.File
            {
                Name        = file.FileName,
                Path        = path,
                ContentType = GetContentType(path).ToString()
            };

            _libraryRepository.AddFileAsync(filedb);
            if (!(await _libraryRepository.SaveAsync()))
            {
                throw new Exception("Failed to save file data to db");
            }

            return(Ok());
        }