public static void PutBucketItem(string itemKey, string bucketName, Stream uploadContent, Action<ProgressResponse> progressHandler = null)
        {
            var uploadRequest = new TransferUtilityUploadRequest()
                .WithBucketName(bucketName)
                .WithKey(itemKey);

            try
            {

                var awsClient = AWSClientFactory.CreateAmazonS3Client(Properties.Resources.AmazonAccessKeyId,
                                                      Properties.Resources.SecretAccessKeyId,
                                                      new AmazonS3Config().WithCommunicationProtocol
                                                          (Protocol.HTTP));

                var fileTransferUtility =
                    new TransferUtility(awsClient);

                uploadRequest.UploadProgressEvent += (s, e) =>
                                                         {
                                                             var r = new ProgressResponse
                                                                         {
                                                                             BytesSent = e.TransferredBytes,
                                                                             ProgressPercentage = e.PercentDone,
                                                                             TotalBytesToSend = e.TotalBytes
                                                                         };
                                                             if (progressHandler != null) progressHandler(r);
                                                         };

                uploadRequest.WithInputStream(uploadContent);
                fileTransferUtility.Upload(uploadRequest);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Exception occur writing to amazon S3 server\nException: {0}\nStacktrace: {1}", ex.Message, ex.StackTrace);
                throw;
            }
        }
Beispiel #2
0
        private void Upload(IFileStreamWrap stream, string bucketName, string key, bool setPublicAccess)
        {
            try
            {
                key = key.ToLowerInvariant();

                var existsResponse = FileExists(bucketName, key);
                if (existsResponse != null && existsResponse.ContentLength == stream.Length)
                {
                    Logger.Log(string.Format("Skipping {0} because it already exists in {1}", key, bucketName));
                    return;
                }

                var uploadRequest = new TransferUtilityUploadRequest();
                uploadRequest.WithInputStream(stream.StreamInstance);
                uploadRequest.WithBucketName(bucketName);
                Logger.Log(String.Format("Bucket {0}", bucketName));
                if (setPublicAccess)
                    uploadRequest.CannedACL = S3CannedACL.PublicRead;
                uploadRequest.Key = key;
                Logger.Log(String.Format("Key {0}", key));
                uploadRequest.WithTimeout(14400000); // 4 Hours

                var lastKnownPercentage = 0;
                uploadRequest.UploadProgressEvent += (s, e) =>
                {
                    if (e.PercentDone <= lastKnownPercentage)
                        return;

                    Logger.Log(String.Format("UploadProgress:{0} :{1}%", key, e.PercentDone));
                    lastKnownPercentage = e.PercentDone;
                };

                TransferUtility.Upload(uploadRequest);
            }
            catch (Exception exception)
            {
                Logger.Log("Error uploading to s3");
                Logger.Log(exception.Message);
                throw;
            }
        }
        public void SaveFiles( List<FileUpload> fileList )
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;
            string accessKeyID = appConfig["AWSAccessKey"];
            string secretAccessKey = appConfig["AWSSecretKey"];
            string s3BucketName = appConfig["AWSBucketName"];

            if ( accessKeyID == null || secretAccessKey == null || s3BucketName == null )
            {
                throw new ConfigurationErrorsException( "One or more keys (AWSAccessKey, AWSSecretKey, and/or AWSBucketName) missing from web.config." );
            }

            // This is used to delete old items.
            AmazonS3 s3Client = Amazon.AWSClientFactory.CreateAmazonS3Client( accessKeyID, secretAccessKey );
            TransferUtility fileTransferUtility = new TransferUtility( accessKeyID, secretAccessKey );

            foreach ( FileUpload fileUpload in fileList )
            {
                try
                {
                    string fileExtension = Path.GetExtension( fileUpload.File.FileName );
                    string newFileName = string.Format( "{0}{1}", Guid.NewGuid().ToString(), fileExtension );

                    using ( Stream fileToUpload = fileUpload.File.InputStream )
                    {
                        // We can't do this next line because I want to set the file to public read access
                        // using the TransferUtilityUploadRequest.
                        //fileTransferUtility.Upload( fileToUpload, s3BucketName, newFileName );
                        TransferUtilityUploadRequest fileTransferUtilityRequest =
                            new TransferUtilityUploadRequest()
                                .WithBucketName( s3BucketName )
                                .WithStorageClass( S3StorageClass.ReducedRedundancy )
                                .WithMetadata( "original", fileUpload.File.FileName )
                                .WithKey( newFileName )
                                .WithCannedACL( S3CannedACL.PublicRead );
                        fileTransferUtilityRequest.WithInputStream( fileToUpload );

                        fileTransferUtility.Upload( fileTransferUtilityRequest );
                    }

                    // Success!  Now let's tell the fileUpload what his new public filename will be...
                    fileUpload.NewFileName = string.Format( "https://s3.amazonaws.com/{0}/{1}", s3BucketName, newFileName );
                }
                catch ( AmazonS3Exception s3Exception )
                {
                    fileUpload.IsError = true;
                    fileUpload.ErrorMessage = "Unable to save file: " + s3Exception.Message;
                }

                // Try to delete the old file
                if (fileUpload.PreviousFileName != null &&
                    fileUpload.PreviousFileName.ToLower().Contains( "s3.amazonaws.com" ) )
                {
                    try
                    {
                        DeleteObjectRequest request = new DeleteObjectRequest();
                        string previousKey = Path.GetFileName( fileUpload.PreviousFileName );
                        request.WithBucketName( s3BucketName ).WithKey( previousKey );
                        s3Client.DeleteObject( request );
                    }
                    catch ( AmazonS3Exception aS3Ex ) // that's ok, it's just a low priority cleanup operation
                    {
                        Elmah.ErrorSignal.FromCurrentContext().Raise( aS3Ex );
                    }

                }
            }
        }