Esempio n. 1
0
        private static async Task UploadFileAsync()
        {
            try
            {
                var fileTransferUtility =
                    new TransferUtility(s3Client);

                // Option 2. Specify object key name explicitly.
                await fileTransferUtility.UploadAsync(filePath, bucketName, keyName);

                Console.WriteLine("Upload 2 completed");
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Esempio n. 2
0
        public async Task <string> UploadFileAsync(byte[] inputData, string keyName)
        {
            try
            {
                Stream input = new MemoryStream(inputData);
                var    fileTransferUtility = new TransferUtility(s3Client);
                await fileTransferUtility.UploadAsync(input, bucketName, keyName);

                return(null);
            }
            catch (AmazonS3Exception e)
            {
                logger.Log(LogLevel.Error, $"Error encountered on server. Message:'{e.Message}' when writing an object");
                return(e.ToString());
            }
            catch (Exception e)
            {
                logger.Log(LogLevel.Error, $"Unknown encountered on server. Message:'{e.Message}' when writing an object");
                return(e.ToString());
            }
        }
        /// <summary>
        /// Saves the stream to S3 Object
        /// </summary>
        /// <param name="memoryStream"></param>
        /// <param name="folder"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task <string> SaveStreamToFile(Stream memoryStream, string folder = null, string fileName = null)
        {
            try
            {
                var bucketName = _s3CsvDataFileConfiguration.DataFileLocation;
                var keyName    = fileName ?? Guid.NewGuid() + ".txt";
                var filePath   = folder ?? _s3CsvDataFileConfiguration.OutputFileFolder;

                var fileTransferUtility = new TransferUtility(_amazonS3Client);
                memoryStream.Seek(0, SeekOrigin.Begin);

                await fileTransferUtility.UploadAsync(memoryStream, bucketName, filePath + "/" + keyName);

                return(filePath + "/" + keyName);
            }
            catch (AmazonS3Exception e)
            {
                _logger.LogError("GetStudentGradesFromCsvFile - Error occurred writing file to S3 - {Error}", e);
                throw;
            }
        }
Esempio n. 4
0
        public async Task <string> Upload(MemoryStream file, string fileName)
        {
            using var client = new AmazonS3Client(EnvironmentVariables.AwsAccessKeyId,
                                                  EnvironmentVariables.AwsSecretAccessKey, RegionEndpoint.SAEast1);
            using var tinyClient = new TinyPngClient(EnvironmentVariables.TinyPngApiKey);

            var response = await tinyClient.Compress(file.ToArray()).Download().GetImageStreamData();

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = response,
                Key         = $"uploads/{fileName}",
                BucketName  = EnvironmentVariables.AwsBucketName,
                CannedACL   = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);

            return("https://s3-sa-east-1.amazonaws.com/traba.io/uploads/" + fileName);
        }
        public static async Task UploadFileToS3(IFormFile file, string key)
        {
            using (var client = new AmazonS3Client("AKIAWOOZGGP3DE67XJ6O", "4SXKP3xXZ1F/X/YfNPQHbqg3NPntmrXOUIMUtpVL", RegionEndpoint.USEast1))
            {
                using (var newMemoryStream = new MemoryStream())
                {
                    file.CopyTo(newMemoryStream);

                    var uploadRequest = new TransferUtilityUploadRequest
                    {
                        InputStream = newMemoryStream,
                        Key         = key + file.FileName,
                        BucketName  = "contestplatformcontests",
                        CannedACL   = S3CannedACL.NoACL
                    };

                    var fileTransferUtility = new TransferUtility(client);
                    await fileTransferUtility.UploadAsync(uploadRequest);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Save file to amazon.
        /// </summary>
        /// <param name="fileStream">The file bytes.</param>
        /// <param name="filename">The fime name.</param>
        /// <param name="contentType">The content type.</param>
        /// <returns>The file url.</returns>
        private async Task <string> SaveFileToAmazon(byte[] fileStream, string filename, string contentType)
        {
            // Upload image to amazon aws s3 bucket
            using (var client = AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretAccessKey, RegionEndpoint.USEast1))
            {
                TransferUtility utility = new TransferUtility(client);
                TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
                using (var stream = new MemoryStream(fileStream))
                {
                    request.BucketName  = AWSBucketName;
                    request.Key         = filename;
                    request.InputStream = stream;
                    request.ContentType = contentType;
                    await utility.UploadAsync(request);
                }
                utility.Dispose();
                request.AutoCloseStream = true;
            }

            return(AWSUrl + filename);
        }
Esempio n. 7
0
        public async Task UploadFileToS3(IFormFile file)
        {
            using (var client = new AmazonS3Client("ASIAUMDIRDA44BKH3D5V", "HClz97bFcQk0Hza5bkaf1g7FhOpmFPEEQ4H25gvi", RegionEndpoint.USEast1))
            {
                using (var newMemoryStream = new MemoryStream())
                {
                    file.CopyTo(newMemoryStream);

                    var uploadRequest = new TransferUtilityUploadRequest
                    {
                        InputStream = newMemoryStream,
                        Key         = file.FileName,
                        BucketName  = "bukectmyportfolio",
                        CannedACL   = S3CannedACL.PublicRead
                    };

                    var fileTransferUtility = new TransferUtility(client);
                    await fileTransferUtility.UploadAsync(uploadRequest);
                }
            }
        }
        private async Task <string> UploadFileToS3(IFormFile file)
        {
            var             key = Guid.NewGuid().ToString() + separationString + GetValidFileName(file.FileName);
            TransferUtility fileTransferUtility;

            try
            {
                fileTransferUtility = new TransferUtility(s3Client);
                using (var fileToUpload = file.OpenReadStream())
                {
                    await fileTransferUtility.UploadAsync(fileToUpload, bucketName, key);
                }
            }
            catch (Exception)
            {
                throw new FileLoadException();
            }

            fileTransferUtility.Dispose();
            return(key);
        }
Esempio n. 9
0
        private static async Task UploadFileAsync(string filePath, string bucketName, string keyName)
        {
            try
            {
                var fileTransferUtility = new TransferUtility(s3Client);

                await fileTransferUtility.UploadAsync(filePath, bucketName);

                Log.Information("Upload 2 completed");
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
                Log.Error("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                Log.Error("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Esempio n. 10
0
        public async Task <string> UploadImage(IFormFile file)
        {
            var newMemoryStream = new MemoryStream();
            await file.CopyToAsync(newMemoryStream);

            string uniqueName    = Guid.NewGuid().ToString() + "_" + file.FileName;
            var    uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = newMemoryStream,
                Key         = uniqueName,
                ///Bucket name
                BucketName = "Bucket name",
                CannedACL  = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(s3Client);
            await fileTransferUtility.UploadAsync(uploadRequest);

            //Returns the files url when it gets uploaded to s3 bucket
            return(filePath + uploadRequest.Key);
        }
Esempio n. 11
0
        /// <summary>
        /// S3 doesnt support this natively and will cache everything in MemoryStream until disposed.
        /// </summary>
        public Task <Stream> OpenWriteAsync(string fullPath, bool append = false, CancellationToken cancellationToken = default)
        {
            if (append)
            {
                throw new NotSupportedException();
            }
            GenericValidation.CheckBlobFullPath(fullPath);
            fullPath = StoragePath.Normalize(fullPath, false);

            //http://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html

            var callbackStream = new FixedStream(new MemoryStream(), null, async(fx) =>
            {
                var ms      = (MemoryStream)fx.Parent;
                ms.Position = 0;

                await _fileTransferUtility.UploadAsync(ms, _bucketName, fullPath, cancellationToken).ConfigureAwait(false);
            });

            return(Task.FromResult <Stream>(callbackStream));
        }
Esempio n. 12
0
        public async Task UploadFileToS3(IFormFile file)
        {
            using (var client = new AmazonS3Client(BucketInfo.AWSKey, BucketInfo.AWSSKey, RegionEndpoint.USEast2))
            {
                using (var newMemoryStream = new MemoryStream())
                {
                    file.CopyTo(newMemoryStream);

                    var uploadRequest = new TransferUtilityUploadRequest
                    {
                        InputStream = newMemoryStream,
                        Key         = file.FileName,
                        BucketName  = BucketInfo.Bucket,
                        CannedACL   = S3CannedACL.PublicRead
                    };

                    var fileTransferUtility = new TransferUtility(client);
                    await fileTransferUtility.UploadAsync(uploadRequest);
                }
            }
        }
        public async Task <IActionResult> CovertDoc(List <IFormFile> files)
        {
            if (!files.Any())
            {
                return(View());
            }
            var doc = files[0];
            var key = doc.FileName;//key is full folder path on S3

            var utility = new TransferUtility(_s3Client);
            await utility.UploadAsync(doc.OpenReadStream(), _bucket, key);

            var req = new InvokeRequest
            {
                FunctionName = "your_lambda_funtion_name",
                Payload      = JsonSerializer.Serialize(new { key, bucket = _bucket }),
            };
            var res = await _lambdaClient.InvokeAsync(req);

            using var sr = new StreamReader(res.Payload);
            var resString = await sr.ReadToEndAsync();

            var pdfKey = JsonSerializer.Deserialize <string>(resString);// my lambda return converted pdf S3 key

            var preSignedUrlRequest = new GetPreSignedUrlRequest
            {
                BucketName = _bucket,
                Key        = pdfKey,
                Expires    = DateTime.Now.AddDays(1),
                ResponseHeaderOverrides = new ResponseHeaderOverrides()
                {
                    ContentType        = "application/force-download",
                    ContentDisposition = "attachment;filename=" + "download_file_name"
                }
            };
            var preSignedUrl = _s3Client.GetPreSignedURL(preSignedUrlRequest);//downloadable S3 file url

            ViewBag.pdfUrl = preSignedUrl;
            return(View("Convert-Pdf"));
        }
Esempio n. 14
0
        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var file = new FileInfo(FileName);

            FileSize = Tools.SizeToHuman(file.Length);

            Status = "Uploading";

            using (var fileTransferUtility = new TransferUtility(_client))
            {
                var uploadRequest =
                    new TransferUtilityUploadRequest
                {
                    BucketName      = _awsbucket,
                    FilePath        = file.FullName,
                    Key             = $"{_prefix}/{file.Name}",
                    CannedACL       = S3CannedACL.Private,
                    ContentType     = MimeMapping.GetMimeMapping(file.Name),
                    StorageClass    = S3StorageClass.Standard,
                    AutoCloseStream = true,
                    TagSet          = new List <Tag>()
                    {
                        new Tag()
                        {
                            Key   = "MachineName",
                            Value = Environment.MachineName
                        },
                        new Tag()
                        {
                            Key   = "UserName",
                            Value = Environment.UserName
                        }
                    }
                };

                uploadRequest.UploadProgressEvent += uploadRequest_UploadPartProgressEvent;

                fileTransferUtility.UploadAsync(uploadRequest, _tokenSource.Token);
            }
        }
Esempio n. 15
0
        public async Task <APIGatewayProxyResponse> CreateProfileAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            WriteVariables(context);

            string requestBody = request.Body;

            context.Logger.LogLine($"Request Body\n {requestBody}");
            AddProfileModel addProfileModel = JsonConvert.DeserializeObject <AddProfileModel>(requestBody);

            context.Logger.LogLine($"Decoding Base64 image");
            var bytes = Convert.FromBase64String(addProfileModel.ProfilePicBase64);

            var fileTransferUtility = new TransferUtility(_awsS3Client);

            using (var ms = new MemoryStream(bytes))
            {
                context.Logger.LogLine($"Uploading {addProfileModel.ProfilePicName} to {BucketName}");
                await fileTransferUtility.UploadAsync(ms, BucketName, addProfileModel.ProfilePicName);
            }

            context.Logger.LogLine($"Adding profile to DynamoDb");
            await _awsDynamoDbClient.PutItemAsync(TableName, new Dictionary <string, AttributeValue>()
            {
                { nameof(AddProfileModel.Id), new AttributeValue(addProfileModel.Id) },
                { nameof(AddProfileModel.Name), new AttributeValue(addProfileModel.Name) },
                { nameof(AddProfileModel.Email), new AttributeValue(addProfileModel.Email) },
                { nameof(AddProfileModel.ProfilePicName), new AttributeValue(addProfileModel.ProfilePicName) }
            });

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = "Created",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                }
            };

            return(response);
        }
Esempio n. 16
0
 public async Task UploadFileAsync(string emailId)
 {
     try
     {
         var uploadRequest = new TransferUtilityUploadRequest
         {
             FilePath   = filePath,
             BucketName = bucketName,
             Key        = keyName,
             CannedACL  = S3CannedACL.PublicRead
         };
         var fileTransferUtility = new TransferUtility(s3Client);
         await Task.Run(() =>
         {
             Task upld = fileTransferUtility.UploadAsync(uploadRequest);
             while (!upld.IsCompleted)
             {
                 upld.Wait(25); if (upld.IsFaulted || upld.IsCanceled)
                 {
                     return;
                 }
             }
             Trace.WriteLine(String.Format("Upload status: {0} \n Upload Complete: {1}", upld.Status, upld.IsCompleted));
             AWSConnectionService.getInstance().ListPDFFilesforUser(emailId);
             Console.WriteLine("File Upload completed.. Check bucket via console");
             Application.Current.Dispatcher.Invoke((Action) delegate
             {
                 new Welcome(emailId).Show();
             });
         });
     }
     catch (AmazonS3Exception e)
     {
         Trace.WriteLine(String.Format("Error encountered on server. Message: '{0}' when writing an object", e.Message));
     }
     catch (Exception e)
     {
         Trace.WriteLine(String.Format("Unknown encountered on server. Message: '{0}' when writing an object", e.Message));
     }
 }
Esempio n. 17
0
        public async Task Deliver(Uri destination, MsgNThenMessage message)
        {
            //https://s3.us-east-2.amazonaws.com/my-bucket-name/filename
            //s3://john.doe@my-bucket-name/filename[
            //s3://<credentialName>@<bucketname>/filename
            var credentials     = GetCredentials(destination);
            var bucketName      = destination.Host;
            var pathAndQuery    = Uri.UnescapeDataString(destination.PathAndQuery).TrimStart('/');
            var messageId       = message.Headers[HeaderConstants.MessageId];
            var messageGroupId  = message.Headers[HeaderConstants.MessageGroupId];
            var correlationId   = message.Headers[HeaderConstants.CorrelationId];
            var fileKey         = string.Format(pathAndQuery, messageId, messageGroupId, correlationId);
            var queryDictionary = QueryHelpers.ParseQuery(destination.Query);

            if (message.Body.CanSeek)
            {
                message.Body.Position = 0;
            }
            using (var client = new AmazonS3Client(credentials.awsAccessKeyId, credentials.awsSecretAccessKey, RegionEndpoint.USEast1))
            {
                var uploadRequest = new TransferUtilityUploadRequest
                {
                    InputStream = message.Body,
                    Key         = fileKey,
                    BucketName  = bucketName,
                    CannedACL   = S3CannedACL.BucketOwnerFullControl
                };
                if (queryDictionary.TryGetValue(QueryConstants.S3CannedACL, out var val))
                {
                    var cannedAcl = S3CannedACL.FindValue(val);
                    if (cannedAcl != null)
                    {
                        uploadRequest.CannedACL = cannedAcl;
                    }
                }

                var fileTransferUtility = new TransferUtility(client);
                await fileTransferUtility.UploadAsync(uploadRequest);
            }
        }
        public static async Task UploadFileAsync(
            IAmazonS3 client,
            string bucketName,
            string key,
            string contentType,
            string contentEncoding,
            Stream reader,
            ServerSideEncryptionMethod serverSideEncryptionMethod,
            CancellationToken token)
        {
            var transferUtility = new TransferUtility(client);
            var request         = new TransferUtilityUploadRequest
            {
                BucketName              = bucketName,
                Key                     = key,
                InputStream             = reader,
                AutoCloseStream         = false,
                AutoResetStreamPosition = false,
                Headers                 = { CacheControl = "no-store" }
            };

            if (serverSideEncryptionMethod != ServerSideEncryptionMethod.None)
            {
                request.ServerSideEncryptionMethod = serverSideEncryptionMethod;
            }

            if (contentType != null)
            {
                request.ContentType         = contentType;
                request.Headers.ContentType = contentType;
            }

            if (contentEncoding != null)
            {
                request.Headers.ContentEncoding = contentEncoding;
            }

            using (transferUtility)
                await transferUtility.UploadAsync(request, token).ConfigureAwait(false);
        }
Esempio n. 19
0
    public async Task <bool> UploadFileAsync(Stream fileStream, string fileName, string directory = null)
    {
        try
        {
            var fileTransferUtility = new TransferUtility(_s3Client);
            var bucketPath          = !string.IsNullOrWhiteSpace(directory)
                ? _s3BucketOptions.BucketName + @"/" + directory
                : _s3BucketOptions.BucketName;

            var fileUploadRequest = new TransferUtilityUploadRequest()
            {
                CannedACL  = S3CannedACL.PublicRead,
                BucketName = bucketPath,
                Key        = fileName,
                //PartSize = 26214400,
                InputStream = fileStream
            };
            fileUploadRequest.UploadProgressEvent += (sender, args) =>
                                                     _logger.LogInformation($"{args.FilePath} upload complete : {args.PercentDone}%");
            await fileTransferUtility.UploadAsync(fileUploadRequest);

            _logger.LogInformation($"successfully uploaded {fileName} to {bucketPath} on {DateTime.UtcNow:O}");
            return(true);
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                 amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                _logger.LogError("Please check the provided AWS Credentials.");
            }
            else
            {
                _logger.LogError(
                    $"An error occurred with the message '{amazonS3Exception.Message}' when uploading {fileName}");
            }
            return(false);
        }
    }
Esempio n. 20
0
        private async Task <IActionResult> UploadByteAsync(string keyName)
        {
            try
            {
                string     path = Path.Combine(this.hostingEnvironment.ContentRootPath, keyName);
                FileStream fs   = new FileStream(path, FileMode.Open);
                var        fileTransferUtility        = new TransferUtility(this.s3Client);
                var        fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName   = bucketName,
                    InputStream  = fs,
                    StorageClass = S3StorageClass.Standard,
                    Key          = keyName,
                    CannedACL    = S3CannedACL.PublicRead
                };


                await fileTransferUtility.UploadAsync(fileTransferUtilityRequest);

                fs.Close();
                System.IO.File.Delete(path);
                return(Ok(new ServiceResponse {
                    Status = "success", Message = $"https://s3.ap-south-1.amazonaws.com/{bucketName}/{keyName}"
                }));
            }
            catch (AmazonS3Exception e)
            {
                this.logger.Log("UploadByteAsync Amazon has Problem", e.Message, e.InnerException?.Message);
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                this.logger.Log("UploadByteAsync has Problem", e.Message, e.InnerException?.Message);
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }

            return(Ok(new ServiceResponse {
                Status = "error", Message = "Something Went Wrong When Uploading The File"
            }));
        }
Esempio n. 21
0
        private async void UploadFile(string bucketName)
        {
            OpenFileDialog choofdlog = new OpenFileDialog();

            choofdlog.Filter      = "All Files (*.*)|*.*";
            choofdlog.FilterIndex = 1;
            choofdlog.Multiselect = false;

            if (choofdlog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var fileTransferUtility = new TransferUtility(client);

                    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
                    {
                        BucketName = bucketName,
                        FilePath   = choofdlog.FileName,
                        Key        = choofdlog.SafeFileName
                    };
                    request.UploadProgressEvent +=
                        new EventHandler <UploadProgressArgs>
                            (uploadRequest_UploadPartProgressEvent);

                    EnableProgressBar();
                    await fileTransferUtility.UploadAsync(request);

                    MessageBox.Show("Upload Completed");
                    ResetProgressBar();
                }
                catch (AmazonS3Exception e)
                {
                    MessageBox.Show($"Error encountered on server. Message:'{e.Message}' when writing an object");
                }
                catch (Exception e)
                {
                    MessageBox.Show($"Unknown encountered on server. Message:'{e.Message}' when writing an object");
                }
            }
        }
Esempio n. 22
0
        private static readonly IAmazonS3 S3Client         = new AmazonS3Client(BucketRegion);  // Instantiating S3 Client

        public static async Task <int> UploadingFileAsync()                                     // Method to upload files to S3 bucket
        {
            try
            {
                var fileTransferUtility = new TransferUtility(S3Client);
                await fileTransferUtility.UploadAsync(FilePath, bucketName);

                return(0);
            }

            catch (AmazonS3Exception exception)
            {
                Console.Error.WriteLine("Error encountered on server. Message:'{0}' when writing an object", exception.Message);
                return(-1);
            }

            catch (Exception exception)
            {
                Console.Error.WriteLine("Unknown error encountered on server. Message:'{0}' when writing an object", exception.Message);
                return(-1);
            }
        }
        public async Task <string> SafePhoto(string photo)
        {
            var bytes     = Convert.FromBase64String(photo.Split(',')[1]);
            var photoName = GetHashedName(bytes) + "." + Regex.Match(photo, @"data:.*?/(?<ext>.*?);base64").Groups["ext"].Value;

            using (var stream = new MemoryStream(bytes))
            {
                using (var fileTransferUtility = new TransferUtility(_client))
                {
                    var awsRequest = new TransferUtilityUploadRequest()
                    {
                        BucketName  = BucketName,
                        Key         = photoName,
                        InputStream = stream
                    };
                    awsRequest.CannedACL = "public-read";
                    await fileTransferUtility.UploadAsync(awsRequest);
                }
            }

            return(photoName);
        }
Esempio n. 24
0
        public async Task <String> SaveToBlobAsync(string bucketDestino, MemoryStream filePath, string contentType)
        {
            try
            {
                TransferUtility fileTransferUtility = new
                                                      TransferUtility(new AmazonS3Client(ConfigurationManager.AppSettings["awsAccessKeyId"].ToString(), ConfigurationManager.AppSettings["awsSecretAccessKey"].ToString(), Amazon.RegionEndpoint.SAEast1)
                                                                      );

                string nomeArquivo = Guid.NewGuid().ToString();
                nomeArquivo = nomeArquivo + "." + contentType;
                await fileTransferUtility.UploadAsync(filePath, bucketDestino, nomeArquivo);

                string url = @"https://s3-sa-east-1.amazonaws.com/";
                url += bucketDestino + "/" + nomeArquivo;
                return(url);
            }
            catch (AmazonS3Exception s3Exception)
            {
                var x = s3Exception.Message;
                return("Error" + x);
            }
        }
Esempio n. 25
0
        protected override async Task <bool> DoSaveAsync(string path, Stream file,
                                                         CancellationToken?cancellationToken = null)
        {
            await CreateBucketAsync(Options.Bucket, cancellationToken);

            using var fileTransferUtility = new TransferUtility(_s3Client);
            try
            {
                var request = new TransferUtilityUploadRequest
                {
                    InputStream = file, Key = path, BucketName = Options.Bucket
                };
                await fileTransferUtility.UploadAsync(request, cancellationToken ?? CancellationToken.None);

                return(true);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error uploading file {File}: {ErrorText}", path, e.ToString());
                throw;
            }
        }
Esempio n. 26
0
        public async Task UploadFile(Stream fileStream, string key, string mimeType)
        {
            TransferUtility fileTransferUtility = new TransferUtility(this.amazonS3);

            TransferUtilityUploadRequest uploadRequest = new TransferUtilityUploadRequest()
            {
                InputStream = fileStream,
                BucketName  = this.configuration.GetSection("AWS")
                              .GetSection("S3")
                              .GetSection("Bucket")
                              .GetValue <string>("Name"),
                Key             = key,
                ContentType     = mimeType,
                AutoCloseStream = true
            };

            this.logger.LogInformation("Starting file upload to AWS S3 storage bucket: " + key + " (" + mimeType + ")");

            await fileTransferUtility.UploadAsync(uploadRequest);

            this.logger.LogInformation("File uploaded to AWS S3 storage bucket: " + key + " (" + mimeType + ")");
        }
        public async Task <IActionResult> OnPostAsync()
        {
            try
            {
                // 1. upload video to s3
                // TODO check stream processing
                await using var memoryStream = new MemoryStream();
                FileUpload.CopyTo(memoryStream);

                var uploadRequest = new TransferUtilityUploadRequest
                {
                    InputStream = memoryStream,
                    Key         = Title,
                    BucketName  = BucketName,
                    CannedACL   = S3CannedACL.PublicRead
                };

                var ftu = new TransferUtility(_amazonS3);
                await ftu.UploadAsync(uploadRequest);

                // 2. save s3 link in db
                var curUser = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                var video   = new Video
                {
                    S3Url  = $"{Constants.VideoUploadS3BaseUrl}/{Title}",
                    Title  = this.Title,
                    UserId = curUser
                };
                _context.Add(video);
                await _context.SaveChangesAsync();

                return(new RedirectToPageResult("/Index"));
            }
            catch (Exception e)
            {
                // idk handle later
                throw;
            }
        }
Esempio n. 28
0
        public async Task UploadObjectDataAsyncAWSS3(string filename, byte[] bytea, EbFileCategory cat)
        {
            try
            {
                var fileTransferUtility = new TransferUtility(s3Client);
                var ms = new System.IO.MemoryStream();
                ms.Write(bytea, 0, bytea.Length);
                ms.Position = 0;

                await fileTransferUtility.UploadAsync(ms, bucketName, filename);

                Console.WriteLine("Upload 4 completed");
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Esempio n. 29
0
        public async Task <string> UploadFileAsync(string fileName, Stream file)
        {
            var filestream = new MemoryStream();
            await file.CopyToAsync(filestream);

            var s3FileName = $"{DateTime.Now.Ticks}-{fileName}";

            var transferRequest = new TransferUtilityUploadRequest()
            {
                ContentType = "application/octet-stream",
                InputStream = filestream,
                BucketName  = _bucket,
                Key         = s3FileName
            };

            transferRequest.Metadata.Add("x-amz-meta-title", fileName);

            var fileTransferUtility = new TransferUtility(_client);
            await fileTransferUtility.UploadAsync(transferRequest);

            return(s3FileName);
        }
Esempio n. 30
0
        /// <summary>
        /// Adds the image to the cache in an asynchronous manner.
        /// </summary>
        /// <param name="stream">
        /// The stream containing the image data.
        /// </param>
        /// <param name="contentType">
        /// The content type of the image.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/> representing an asynchronous operation.
        /// </returns>
        public override async Task AddImageToCacheAsync(Stream stream, string contentType)
        {
            TransferUtility transferUtility = new TransferUtility(this.amazonS3ClientCache);

            string path     = this.GetFolderStructureForAmazon(this.CachedPath);
            string filename = Path.GetFileName(this.CachedPath);
            string key      = this.GetKey(path, filename);

            TransferUtilityUploadRequest transferUtilityUploadRequest = new TransferUtilityUploadRequest
            {
                BucketName  = this.awsBucketName,
                InputStream = stream,
                Key         = key,
                CannedACL   = S3CannedACL.PublicRead
            };

            transferUtilityUploadRequest.Headers.CacheControl = string.Format("public, max-age={0}", this.MaxDays * 86400);
            transferUtilityUploadRequest.Headers.ContentType  = contentType;
            transferUtilityUploadRequest.Metadata.Add("x-amz-meta-ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion);

            await transferUtility.UploadAsync(transferUtilityUploadRequest);
        }