PutObjectAsync() public method

Initiates the asynchronous execution of the PutObject operation.
public PutObjectAsync ( PutObjectRequest request, System cancellationToken = default(CancellationToken) ) : Task
request PutObjectRequest Container for the necessary parameters to execute the PutObject operation.
cancellationToken System /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. ///
return Task
Exemplo n.º 1
4
        public async Task UploadDataFileAsync(string data, string storageKeyId, string storageSecret, string region)
        {
            var regionIdentifier = RegionEndpoint.GetBySystemName(region);
            using (var client = new AmazonS3Client(storageKeyId, storageSecret, regionIdentifier))
            {
                try
                {
                    var putRequest1 = new PutObjectRequest
                    {
                        BucketName = AwsBucketName,
                        Key = AwsBucketFileName,
                        ContentBody = data,
                        ContentType = "application/json"
                    };

                    await client.PutObjectAsync(putRequest1);
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    if (amazonS3Exception.ErrorCode != null &&
                        (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                    {
                        throw new SecurityException("Invalid Amazon S3 credentials - data was not uploaded.", amazonS3Exception);
                    }

                    throw new HttpRequestException("Unspecified error attempting to upload data: " + amazonS3Exception.Message, amazonS3Exception);
                }

                var response = await client.GetObjectAsync(AwsBucketName, AwsBucketFileName);
                using (var reader = new StreamReader(response.ResponseStream))
                {
                    Debug.WriteLine(await reader.ReadToEndAsync());
                }
            }
        }
        /// <summary>
        /// Allows to upload a Text Object to a S3 Bucket. Object Size is limited to IRIS string size.
        /// https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
        /// </summary>
        /// <param name="key">The Object name in S3</param>
        /// <param name="content">The String to upload as the Object Content</param>
        /// <returns></returns>
        public string PutText(string key, string content)
        {
            LOGINFO("PutText, key=" + key);
            var putRequest = new Amazon.S3.Model.PutObjectRequest
            {
                BucketName  = awsBucket,
                Key         = key,
                ContentBody = content
            };


            var putResponse = s3Client.PutObjectAsync(putRequest).Result;

            return(putResponse.HttpStatusCode.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Save report to S3 Bucket
        /// </summary>
        /// <param name="path">BucketName</param>
        /// <param name="prefix">Bucket Prefix</param>
        /// <param name="name">Key Name</param>
        /// <param name="content">File Content</param>
        /// <param name="overwrite"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public async Task <string> Save(string path, string prefix, string name, string content, bool overwrite = false, CancellationToken ct = default)
        {
            await semaphore.WaitAsync();

            try
            {
                var basePath = $"{prefix}/{name}";
                // too many object will refected by s3 ListObjectV2 API
                //var savePath = overwrite ? basePath : await GetSafeSavePath(path, basePath, 1, ct);
                var savePath = basePath;

                _logger?.LogDebug($"uploading content to S3. bucket {path} key {savePath}");
                await _client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
                {
                    BucketName  = path,
                    ContentBody = content,
                    Key         = savePath,
                }, ct);

                return($"https://{path}.s3-ap-northeast-1.amazonaws.com/{savePath}");
            }
            finally
            {
                semaphore.Release();
            }
        }
Exemplo n.º 4
0
        public void Store(string key, byte[] data)
        {
            Amazon.S3.AmazonS3Client client = getS3Client();
            var resTask = client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest()
            {
                BucketName  = bucketName,
                Key         = key,
                InputStream = new MemoryStream(data),
            });
            bool      error          = false;
            Exception innerException = null;

            try
            {
                resTask.Wait();
            }
            catch (Exception ex)
            {
                innerException = ex;
            }
            if (error || resTask.Result.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                if (innerException == null)
                {
                    innerException = resTask.Exception;
                }
                var newEx = new Exception("Store failed, error code: " + resTask.Result.HttpStatusCode, innerException);

                Logger.Error(newEx, "Error storing in S3 bucket, bucket name=" + bucketName + ", key=" + key);
                throw newEx;
            }
        }
Exemplo n.º 5
0
        public async Task UploadFile(string filePath, string s3Bucket, string newFileName, bool deleteLocalFileOnSuccess)
        {
            //save in s3
            Amazon.S3.Model.PutObjectRequest s3PutRequest = new Amazon.S3.Model.PutObjectRequest();
            s3PutRequest            = new Amazon.S3.Model.PutObjectRequest();
            s3PutRequest.FilePath   = filePath;
            s3PutRequest.BucketName = s3Bucket;
            //s3PutRequest.ContentType = contentType;

            //key - new file name
            if (!string.IsNullOrWhiteSpace(newFileName))
            {
                s3PutRequest.Key = newFileName;
            }

            s3PutRequest.Headers.Expires = new DateTime(2020, 1, 1);

            try
            {
                Amazon.S3.Model.PutObjectResponse s3PutResponse = await S3Client.PutObjectAsync(s3PutRequest);

                if (deleteLocalFileOnSuccess)
                {
                    //Delete local file
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                //handle exceptions
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            //https://github.com/aws/aws-sdk-net/issues/499
            Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", AWS_Consts.ACCESS_KEY);
            Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", AWS_Consts.SECRET_ACCESS_KEY);
            Environment.SetEnvironmentVariable("AWS_REGION", "us-east-1");
            // https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html
            using (var s3 = new Amazon.S3.AmazonS3Client(Amazon.RegionEndpoint.USEast1)){
                var request = new PutObjectRequest {
                    BucketName = "aws-lightsail",
                    Key        = "keyName",
                    FilePath   = "/SwiftLanguage.pdf"
                };

                request.Metadata.Add("x-amz-meta-title", "swift");
                var response2 = s3.PutObjectAsync(request);
                Console.WriteLine(response2.Result);
            }
            //     var region = "us-east-1";
            //     var request = (HttpWebRequest)WebRequest.Create(string.Format("https://aws-lightsail.s3.{0}.amazonaws.com",region));
            //     request.Method = "POST";
            //     request.Headers.Add("AWSAccessKeyId",AWS_Consts.ACCESS_KEY);

            //     using(var response = (HttpWebResponse)request.GetResponse()){
            //         if(response.StatusCode==HttpStatusCode.OK){
            //             using(var stream = response.GetResponseStream()){
            //                 Console.WriteLine(new StreamReader(stream).ReadToEnd());
            //             }
            //         }
            //         else throw new WebException("Error: "+response.StatusCode);
            //     }
        }
Exemplo n.º 7
0
        public static async Task <string> UploadImageBlobAmazonS3(string fileName, string blobName, List <KeyValuePair <string, string> > metadataTags)
        {
            string bucketName   = ConfigurationManager.AppSettings["AWSMediaItemsContainerName"];
            string accessKey    = ConfigurationManager.AppSettings["AWSAccessKey"];
            string accessSecret = ConfigurationManager.AppSettings["AWSAccessSecret"];

            using (var client = new Amazon.S3.AmazonS3Client(accessKey, accessSecret, Amazon.RegionEndpoint.APSoutheast2))
            {
                //upload: http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html
                try
                {
                    PutObjectRequest putRequest1 = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key        = "images/" + blobName,
                        FilePath   = fileName,
                        CannedACL  = S3CannedACL.PublicRead
                    };

                    PutObjectResponse response1 = await client.PutObjectAsync(putRequest1);

                    return("https://s3-ap-southeast-2.amazonaws.com/openchargemap/images/" + blobName);

                    /* // 2. Put object-set ContentType and add metadata.
                     * PutObjectRequest putRequest2 = new PutObjectRequest
                     * {
                     *   BucketName = bucketName,
                     *   Key = keyName,
                     *   FilePath = filePath,
                     *   ContentType = "text/plain"
                     * };
                     * putRequest2.Metadata.Add("x-amz-meta-title", "someTitle");
                     *
                     * PutObjectResponse response2 = client.PutObject(putRequest2);*/
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    if (amazonS3Exception.ErrorCode != null &&
                        (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                         ||
                         amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                    {
                        Console.WriteLine("Check the provided AWS Credentials.");
                        Console.WriteLine(
                            "For service sign up go to http://aws.amazon.com/s3");
                    }
                    else
                    {
                        Console.WriteLine(
                            "Error occurred. Message:'{0}' when writing an object"
                            , amazonS3Exception.Message);
                    }
                    return(null);
                }
            }
        }
 private async Task<PutObjectResponse> UploadItemAsync(AmazonS3Client s3Client, string bucketName, string path, CancellationToken token)
 {
     using (var contentStream = _itemChange.CreateContentStream())
     {
         var request = new PutObjectRequest()
         {
             BucketName = bucketName,
             Key = path + _itemChange.Item.Path,
             ContentType = _itemChange.Item.ContentMetadata.ContentType,
             InputStream = contentStream
         };
         return await s3Client.PutObjectAsync(request, token);
     }
 }
Exemplo n.º 9
0
        private void uploadContent(String content, String bucket, String key)
        {
            using (var s3client = new Amazon.S3.AmazonS3Client())
            {
                var uploadPromise = s3client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
                {
                    BucketName  = bucket,
                    Key         = key,
                    ContentBody = content
                });

                uploadPromise.Wait();

                Console.WriteLine($"Uploaded s3://{bucket}/{key} ETAG {uploadPromise.Result.ETag}");
            }
        }
Exemplo n.º 10
0
        public static void saveFile()
        {
            string accessKey = "*********************";
            string secretKey = "******************************************";

            AmazonS3Client s3 = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1);

            var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var fileName = Path.Combine(path, "write.txt");
            PutObjectRequest request = new PutObjectRequest{
            BucketName = "calculatorkrao1",
            Key = "EquationList",
                FilePath = fileName,

            };

            System.Threading.Tasks.Task<PutObjectResponse> response = s3.PutObjectAsync(request);
        }
Exemplo n.º 11
0
        public async Task EditFile(string filePath, string contentType, string content)
        {
#pragma warning disable 618 // "'StoredProfileCredentials' is obsolete..."
            var creds = new StoredProfileAWSCredentials("acmesharp-tests");
#pragma warning restore 618
            var reg    = RegionEndpoint.GetBySystemName(AwsRegion);
            var delete = content == null;

            // We need to strip off any leading '/' in the path or
            // else it creates a path with an empty leading segment
            // if (filePath.StartsWith("/"))
            //     filePath = filePath.Substring(1);
            filePath = filePath.Trim('/');

            using (var s3 = new Amazon.S3.AmazonS3Client(creds, reg))
            {
                if (delete)
                {
                    var s3Requ = new Amazon.S3.Model.DeleteObjectRequest
                    {
                        BucketName = BucketName,
                        Key        = filePath,
                    };
                    var s3Resp = await s3.DeleteObjectAsync(s3Requ);
                }
                else
                {
                    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
                    {
                        var s3Requ = new Amazon.S3.Model.PutObjectRequest
                        {
                            BucketName  = BucketName,
                            Key         = filePath,
                            ContentType = contentType,
                            InputStream = ms,
                            CannedACL   = S3CannedAcl,
                        };

                        var s3Resp = await s3.PutObjectAsync(s3Requ);
                    }
                }
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Put(int id, [FromForm] string nome, [FromForm] string cpf, [FromForm] string usuario, [FromForm] string senha, IFormFile file)
        {
            var memoryStream = new MemoryStream();

            file.CopyTo(memoryStream);

            var request = new PutObjectRequest
            {
                BucketName  = "mega-hacka",
                Key         = file.FileName,
                InputStream = memoryStream,
                ContentType = file.ContentType,
                CannedACL   = S3CannedACL.PublicRead
            };

            var s3Client = new Amazon.S3.AmazonS3Client(Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"),
                                                        Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY"),
                                                        Amazon.RegionEndpoint.USEast1);

            var response = await s3Client.PutObjectAsync(request);

            var obj = await _context.Cliente.FindAsync(id);

            if (obj == null)
            {
                return(NotFound());
            }

            obj.CPF       = cpf;
            obj.Nome      = nome;
            obj.Usuario   = usuario;
            obj.Senha     = senha;
            obj.UrlImagem = $"https://mega-hacka.s3.amazonaws.com/{request.Key}";

            _context.Entry(obj).State = EntityState.Modified;
            await _context.SaveChangesAsync();


            return(Ok());
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Post([FromForm] string nome, [FromForm] string cpf, [FromForm] string usuario, [FromForm] string senha, IFormFile file)
        {
            var memoryStream = new MemoryStream();

            file.CopyTo(memoryStream);

            var request = new PutObjectRequest
            {
                BucketName  = "mega-hacka",
                Key         = file.FileName,
                InputStream = memoryStream,
                ContentType = file.ContentType,
                CannedACL   = S3CannedACL.PublicRead
            };



            var s3Client = new Amazon.S3.AmazonS3Client(Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"),
                                                        Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY"),
                                                        Amazon.RegionEndpoint.USEast1);

            var response = await s3Client.PutObjectAsync(request);

            var cliente = new Cliente();

            cliente.Nome      = nome;
            cliente.CPF       = cpf;
            cliente.Usuario   = usuario;
            cliente.Senha     = senha;
            cliente.UrlImagem = $"https://mega-hacka.s3.amazonaws.com/{request.Key}";

            await _context.Cliente.AddAsync(cliente);

            await _context.SaveChangesAsync();

            return(CreatedAtAction("Get", new { id = cliente.Id }));
        }
 public async Task CopyApplicationToBucketAsync(string packagePath)
 {
     using (var s3Client = new AmazonS3Client(credentials, s3ConfigurationProvider.RegionEndpoint))
     {
         var putObjectRequest = new PutObjectRequest
         {
             BucketName = s3ConfigurationProvider.BucketName,
             Key = s3ConfigurationProvider.FullKeyPath,
             FilePath = packagePath
         };
         await s3Client.PutObjectAsync(putObjectRequest);
     }
 }