protected override void Dispose(bool disposing) { base.Dispose(disposing); awsLambdaClient.Dispose(); fileTransferUtility.Dispose(); awsS3Client.Dispose(); }
public async Task <bool> UploadDocument(Stream stream, string fileName) { try { s3Client = new AmazonS3Client(accessKey, secretKey, bucketRegion); TransferUtility transferUtility = new TransferUtility(s3Client); //Set partSize to 5 MB long partSize = 5 * 1024 * 1024; TransferUtilityUploadRequest transferUtilityUploadRequest = new TransferUtilityUploadRequest { BucketName = bucketName, InputStream = stream, StorageClass = S3StorageClass.Standard, CannedACL = S3CannedACL.Private, PartSize = partSize, Key = fileName }; await transferUtility.UploadAsync(transferUtilityUploadRequest); transferUtility.Dispose(); return(true); } catch (Exception ex) { //Log exception return(false); } }
public async Task UploadFileToS3(FileModel fileToUpload) { var filesBucketName = $"helpet/{_environment.EnvironmentName}/docs/{fileToUpload.Folder}/{fileToUpload.Extension}"; var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); try { await fileTransferUtility.S3Client.PutBucketAsync(new PutBucketRequest() { BucketName = "helpet" }); } catch { } fileTransferUtility.Upload(new TransferUtilityUploadRequest() { FilePath = fileToUpload.Path, BucketName = filesBucketName, Key = $"{fileToUpload.Key ?? fileToUpload.Id}.{fileToUpload.Extension}" }); fileTransferUtility.Dispose(); client.Dispose(); }
public void DownloadImageFromS3(ImageModel imageToDownload, bool getThumbnail = false) { var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); var fileName = $"{imageToDownload.Key ?? imageToDownload.Id}.{imageToDownload.Extension}"; if (!getThumbnail) { var imageDownloadDirPath = $"files/images/{imageToDownload.Folder}/{fileName}"; var imagesBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToDownload.Folder}"; fileTransferUtility.Download(imageDownloadDirPath, imagesBucketName, fileName); _imagesCollection.UpdateOne <ImageModel>(image => image.Id == imageToDownload.Id, Builders <ImageModel> .Update.Set("Path", imageDownloadDirPath)); } else { var thumbnailDownloadDirPath = $"files/images/{imageToDownload.Folder}/thumbnails/{fileName}"; var thumbnailsBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToDownload.Folder}/thumbnails"; fileTransferUtility.Download(thumbnailDownloadDirPath, thumbnailsBucketName, fileName); _imagesCollection.UpdateOne <ImageModel>(image => image.Id == imageToDownload.Id, Builders <ImageModel> .Update.Set("ThumbnailPath", thumbnailDownloadDirPath)); } fileTransferUtility.Dispose(); client.Dispose(); }
public void Dispose() { _responseStream.Dispose(); _bufferedStream.Dispose(); _gzipStream.Dispose(); _reader.Dispose(); _transferUtility.Dispose(); }
public void Dispose() { if (_transferUtility != null) { _transferUtility.Dispose(); _transferUtility = null; } }
protected override void DisposeObject(bool disposing) { if (disposing) { s3Client?.Dispose(); transferUtility?.Dispose(); } }
public async Task <StorageClientDownloadResponse> Download(StorageClientDownloadRequest request) { AmazonS3Client s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion); TransferUtility fileTransferUtility = new TransferUtility(s3Client); try { string tempFileLocation = Path.GetTempFileName(); TransferUtilityDownloadRequest fileTransferUtilityRequest = new TransferUtilityDownloadRequest { BucketName = bucketName, FilePath = tempFileLocation, Key = request.DownloadPath }; await fileTransferUtility.DownloadAsync(fileTransferUtilityRequest); fileTransferUtility.Dispose(); byte[] fileData = await File.ReadAllBytesAsync(tempFileLocation); //try clean up try { File.Delete(tempFileLocation); } catch { //not the worse if it fails... } return(new StorageClientDownloadResponse { FilePath = request.DownloadPath, FileData = fileData }); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { return(new StorageClientDownloadResponse { Success = false, Message = "Check the provided AWS Credentials." }); } else { return(new StorageClientDownloadResponse { Success = false, Message = $"Error occurred: {amazonS3Exception.Message}" }); } } }
public void Dispose() { if (_transferUtility != null) { _transferUtility.Dispose(); _transferUtility = null; } if (_amazonS3 != null) { _amazonS3.Dispose(); _amazonS3 = null; } }
public ActionResult UploadFile(string filePath) { // Specify your bucket region (an example region is shown). string bucketName = Configuration.GetValue <string>("BucketName"); RegionEndpoint bucketRegion = RegionEndpoint.USEast1; string accesskey = Configuration.GetValue <string>("AWSAccessKey"); string secretkey = Configuration.GetValue <string>("AWSSecretKey"); var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion); var fileTransferUtility = new TransferUtility(s3Client); try { if (filePath.Length > 0) { // var filePath = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName)); var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName, FilePath = filePath, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = "SampleTest", CannedACL = S3CannedACL.PublicRead }; fileTransferUtilityRequest.Metadata.Add("param1", "Value1"); fileTransferUtilityRequest.Metadata.Add("param2", "Value2"); fileTransferUtility.Upload(fileTransferUtilityRequest); fileTransferUtility.Dispose(); } //ViewBag.Message = "File Uploaded Successfully!!"; } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { //ViewBag.Message = "Check the provided AWS Credentials."; } else { // ViewBag.Message = "Error occurred: " + amazonS3Exception.Message; } } return(RedirectToAction("S3Sample")); }
public async Task <StorageClientUploadResponse> Upload(StorageClientUploadRequest request) { AmazonS3Client s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion); TransferUtility fileTransferUtility = new TransferUtility(s3Client); try { byte[] byteArray = request.StoreContent; using (MemoryStream dataStream = new MemoryStream(byteArray)) { TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName, StorageClass = S3StorageClass.Standard, PartSize = 6291456, // 6 MB Key = request.FileName, CannedACL = S3CannedACL.Private, ContentType = "text/html", InputStream = dataStream }; await fileTransferUtility.UploadAsync(fileTransferUtilityRequest); fileTransferUtility.Dispose(); } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { return(new StorageClientUploadResponse { Success = false, Message = "Check the provided AWS Credentials." }); } else { return(new StorageClientUploadResponse { Success = false, Message = $"Error occurred: {amazonS3Exception.Message}" }); } } return(new StorageClientUploadResponse { Success = true }); }
internal void UploadFileOnCloud(tbl_datakey objtbl_datakey, byte[] encrypted, HttpPostedFileBase file) { string keyName = Path.GetFileName(file.FileName).Split('.')[0] + "_" + objtbl_datakey.tbldatakey_id + "." + Path.GetFileName(file.FileName).Split('.')[1]; Stream stream = new MemoryStream(encrypted); string bucketName = ConfigurationManager.AppSettings["BucketName"]; RegionEndpoint bucketRegion = RegionEndpoint.USEast1; string accesskey = ConfigurationManager.AppSettings["AWSAccessKey"]; string secretkey = ConfigurationManager.AppSettings["AWSSecretKey"]; string sessionToken = ConfigurationManager.AppSettings["AWSSessionToken"]; var s3Client = new AmazonS3Client(accesskey, secretkey, sessionToken, bucketRegion); var fileTransferUtility = new TransferUtility(s3Client); try { if (file.ContentLength > 0) { var fileTransferUtilityRequest = new TransferUtilityUploadRequest { InputStream = stream, BucketName = bucketName, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = keyName, CannedACL = S3CannedACL.PublicRead, ContentType = "text/plain;charset=utf-8" }; fileTransferUtility.Upload(fileTransferUtilityRequest); fileTransferUtility.Dispose(); } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Check the provided AWS Credentials."); } else { Console.WriteLine("Error occurred: " + amazonS3Exception.Message); } } }
public void DownloadFileFromS3(FileModel fileToDownload) { var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); var fileName = $"{fileToDownload.Key ?? fileToDownload.Id}.{fileToDownload.Extension}"; var fileDownloadDirPath = $"files/docs/{fileToDownload.Folder}/{fileToDownload.Extension}/{fileName}"; var filesBucketName = $"helpet/{_environment.EnvironmentName}/docs/{fileToDownload.Folder}/{fileToDownload.Extension}"; fileTransferUtility.Download(fileDownloadDirPath, filesBucketName, fileName); _filesCollection.UpdateOne <FileModel>(document => document.Id == fileToDownload.Id, Builders <FileModel> .Update.Set("Path", fileDownloadDirPath)); fileTransferUtility.Dispose(); client.Dispose(); }
public void UploadToBucket(IFormFile file, string keyName) { var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion); var fileTransferUtility = new TransferUtility(s3Client); try { //if (file.ContentLength > 0) //{ var filePath = "~/Images";// Path.Combine("~/Images", Path.GetFileName(file.FileName)); //Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName)); var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName, FilePath = filePath, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = keyName, CannedACL = S3CannedACL.PublicRead }; fileTransferUtilityRequest.Metadata.Add("param1", "Value1"); fileTransferUtilityRequest.Metadata.Add("param2", "Value2"); fileTransferUtility.Upload(fileTransferUtilityRequest); fileTransferUtility.Dispose(); //} ViewBag.Message = "File Uploaded Successfully!!"; } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { ViewBag.Message = "Check the provided AWS Credentials."; } else { ViewBag.Message = "Error occurred: " + amazonS3Exception.Message; } } }
public async Task UploadImageToS3(ImageModel imageToUpload) { var imagesBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToUpload.Folder}"; var thumbnailsBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToUpload.Folder}/thumbnails"; var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); try { await fileTransferUtility.S3Client.PutBucketAsync(new PutBucketRequest() { BucketName = "helpet" }); } catch { } if (!string.IsNullOrWhiteSpace(imageToUpload.Path)) { fileTransferUtility.Upload(new TransferUtilityUploadRequest() { FilePath = imageToUpload.Path, BucketName = imagesBucketName, Key = $"{imageToUpload.Key ?? imageToUpload.Id}.{imageToUpload.Extension}" }); } if (!string.IsNullOrWhiteSpace(imageToUpload.ThumbnailPath)) { fileTransferUtility.Upload(new TransferUtilityUploadRequest() { FilePath = imageToUpload.ThumbnailPath, BucketName = thumbnailsBucketName, Key = $"{imageToUpload.Key ?? imageToUpload.Id}.{imageToUpload.Extension}" }); } fileTransferUtility.Dispose(); client.Dispose(); }
/// <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); }
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); }
public void UploadFileToS3Bucket(PlayDesign playDesign, string bucketPath, out string uploadFilePath) { uploadFilePath = ""; var file = playDesign.File; try { var s3Cliant = new AmazonS3Client(accesskey, secretkey, bucketRegin); var fileTransferUtility = new TransferUtility(s3Cliant); if (file.Length > 0) { var filePath = Path.Combine(_environment.ContentRootPath, playDesign.FileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { file.CopyTo(fileStream); } var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName + "/" + bucketPath, FilePath = filePath, StorageClass = S3StorageClass.Standard, PartSize = 6291456,// 6 MB CannedACL = S3CannedACL.PublicRead }; fileTransferUtilityRequest.Metadata.Add("param1", "Value1"); fileTransferUtilityRequest.Metadata.Add("param2", "Value2"); fileTransferUtility.Upload(fileTransferUtilityRequest); fileTransferUtility.Dispose(); File.Delete(filePath); uploadFilePath = s3Directory + bucketPath; } } catch (AmazonS3Exception amazonS3Exception) { throw new ISSRepositoryException("AmazonS3への画像アップロードに失敗しました。", amazonS3Exception); } }
public UploadFileResult UploadFile(UploadFileModel uploadFileModel) { string urlfile = ""; string filePath; try { var fileTransferUtility = new TransferUtility(uploadFileModel.AmazonClient); var fileTransferUtilityRequest = SaveFile(uploadFileModel); fileTransferUtility.Upload(fileTransferUtilityRequest); var preSignedURL = GetPreSignedUrl(uploadFileModel); var uploadFileResult = new UploadFileResult(StatusCodes.AWSUploadFileSuccess, preSignedURL); fileTransferUtility.Dispose(); return(uploadFileResult); } catch (GetPreSignedUrlException ex) { } catch (Exception ex) { throw new UploadFileException("An error occured while uploading file"); } return(null); }
/// <summary> /// /// </summary> public void Dispose() { _transferUtility?.Dispose(); GC.SuppressFinalize(this); }
public void Dispose() { transferUtility.Dispose(); }
static void Main(string[] args) { file = new System.IO.StreamWriter(@"C:\TEMP\aws_send2s3.log", true); string Sintaxe = ""; Sintaxe = " " + Environment.NewLine + "SINTAX:" + Environment.NewLine + " " + Environment.NewLine + " > aws_send2s3.exe <mode>,<bucket>,<key>,<secret>,<fullpath> " + Environment.NewLine + " " + Environment.NewLine + "PS.: IF <mode> = 'A' or null, aws_send2s3.config must have config." + Environment.NewLine + " " + Environment.NewLine; PutObjectResponse resposta = null; file.WriteLine("Loading configs..."); Console.WriteLine("Loading configs..."); // Carrega os parâmetros ou exibe mensagem sobre sinxaxe if (!carregouParametros(args)) { if (args.Length.Equals(0)) { Console.WriteLine(Sintaxe); return; } } else { if (!MODO.Equals("A")) { Console.WriteLine(Sintaxe); return; } } if (!File.Exists(caminho_arquivo)) { Console.WriteLine("File not found."); file.WriteLine("File not found."); return; } try { try { transfer = new TransferUtility(Chave, Segredo); file.WriteLine("Generating request to send to " + meuBucket + "..."); Console.WriteLine("Generating request to send to " + meuBucket + "..."); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest() { BucketName = meuBucket, FilePath = caminho_arquivo }; Console.WriteLine("Sending..."); file.WriteLine("Sending..."); transfer.Upload(request); Console.WriteLine("... Sent!"); file.WriteLine("... Sent!"); } catch (Exception ex) { throw ex; } finally { transfer.Dispose(); } Console.WriteLine("/nFile sent!"); file.WriteLine("/nFile sent!"); } catch (Exception ex) { string msgErro = "An error ocourred." + Environment.NewLine + "[INTERNAL_MESSAGE=" + ex.Message.ToString() + Environment.NewLine; if (ex.InnerException != null) { msgErro += "] & [INNER_MESSAGE=" + ex.InnerException.Message.ToString() + Environment.NewLine; } if (ex.StackTrace != null) { msgErro += "] & [STACK_TRACE=" + ex.StackTrace.ToString() + "]"; } if (ex.InnerException == null && ex.StackTrace == null) { msgErro += "]"; } Console.WriteLine(msgErro); file.WriteLine(msgErro); } finally { Console.WriteLine("Answer from S3..."); file.WriteLine("Answer from S3..."); if (resposta == null) { Console.WriteLine("Answer was null."); file.WriteLine("Answer was null."); } else { Console.WriteLine(resposta.ResponseMetadata.ToString()); file.WriteLine(resposta.ResponseMetadata.ToString()); } file.Flush(); file.Dispose(); } }
static void Main(string[] args) { Debug modoDebug = Debug.Desligado; ModalidadeTransferencia modalidadeTransferencia = ModalidadeTransferencia.Download; file = new System.IO.StreamWriter(@"C:\TEMP\aws-getfroms3.log", true); string Sintaxe = ""; Sintaxe = " " + Environment.NewLine + "SINTAX:" + Environment.NewLine + " " + Environment.NewLine + " > aws-getfroms3.exe <mode>,<bucket>,<key>,<secret>,<full-path> " + Environment.NewLine + " " + Environment.NewLine + "PS.: IF <mode> = 'A' or null, config file will be considered." + Environment.NewLine + " " + Environment.NewLine; PutObjectResponse resposta = null; file.WriteLine("Loading configs..."); Console.WriteLine("Loading configs..."); // Carrega os parâmetros ou exibe mensagem sobre sinxaxe if (!carregouParametros(args)) { if (args.Length.Equals(0)) { Console.WriteLine(Sintaxe); return; } } else { if (!MODO.Equals("A")) { Console.WriteLine(Sintaxe); return; } } if (!File.Exists(caminho_arquivo)) { Console.WriteLine("File not found."); file.WriteLine("File not found."); return; } try { try { transfer = new TransferUtility(Chave, Segredo); switch (modalidadeTransferencia) { case ModalidadeTransferencia.Download: file.WriteLine("Creating request to download from bucket " + meuBucket + "..."); Console.WriteLine("Creating request to download from bucket " + meuBucket + "..."); TransferUtilityDownloadRequest requestDownload = new TransferUtilityDownloadRequest() { BucketName = meuBucket, FilePath = caminho_arquivo }; Console.WriteLine("Starting download..."); file.WriteLine("Starting download..."); transfer.Download(requestDownload); Console.WriteLine("... download done."); file.WriteLine("... download done."); Console.WriteLine("/nFile received."); file.WriteLine("/nFile received."); break; case ModalidadeTransferencia.Upload: file.WriteLine("Creating request to upload to bucket " + meuBucket + "..."); Console.WriteLine("Creating request to upload to bucket " + meuBucket + "..."); TransferUtilityUploadRequest requestUpload = new TransferUtilityUploadRequest() { BucketName = meuBucket, FilePath = caminho_arquivo }; Console.WriteLine("Starting sending..."); file.WriteLine("Starting sending..."); transfer.Upload(requestUpload); Console.WriteLine("... file sent."); file.WriteLine("... file sent."); break; } } catch (Exception ex) { throw ex; } finally { transfer.Dispose(); } } catch (Exception ex) { string msgErro = "An error occourred." + Environment.NewLine + "[INTERNAL_MESSAGE=" + ex.Message.ToString() + Environment.NewLine; if (ex.InnerException != null) { msgErro += "] & [INNER_MESSAGE=" + ex.InnerException.Message.ToString() + Environment.NewLine; } if (ex.StackTrace != null) { msgErro += "] & [STACK_TRACE=" + ex.StackTrace.ToString() + "]"; } if (ex.InnerException == null && ex.StackTrace == null) { msgErro += "]"; } Console.WriteLine(msgErro); file.WriteLine(msgErro); } finally { if (modoDebug == Debug.Ligado) { Console.WriteLine("Awswer from S3..."); file.WriteLine("Awswer from S3..."); if (resposta == null) { Console.WriteLine("Awswer from S3 was null."); file.WriteLine("Awswer from S3 was null."); } else { Console.WriteLine(resposta.ResponseMetadata.ToString()); file.WriteLine(resposta.ResponseMetadata.ToString()); } } file.Flush(); file.Dispose(); } }
public override void UploadFile(string filePath, string keyName, object userData, CancellationToken cancellationToken) { if (cancellationToken != null) { cancellationToken.ThrowIfCancellationRequested(); } TransferFileProgressArgs reusedProgressArgs = new TransferFileProgressArgs { UserData = userData, State = TransferState.PENDING, TotalBytes = 0, TransferredBytes = 0, FilePath = filePath, }; TransferUtility fileTransferUtility = null; // IDisposable // REFERENCES: // https://docs.aws.amazon.com/AmazonS3/latest/dev/HLTrackProgressMPUDotNet.html // https://docs.aws.amazon.com/AmazonS3/latest/dev/LLuploadFileDotNet.html try { long fileLength = ZetaLongPaths.ZlpIOHelper.GetFileLength(filePath); reusedProgressArgs.TotalBytes = fileLength; TransferUtilityConfig xferConfig = new TransferUtilityConfig { ConcurrentServiceRequests = 10, // Maximum allowed concurrent requests for this file alone. MinSizeBeforePartUpload = AbsoluteMinPartSize, }; fileTransferUtility = new TransferUtility(this._s3Client, xferConfig); // Step 1: Initialize. // Use TransferUtilityUploadRequest to configure options. TransferUtilityUploadRequest uploadRequest = new TransferUtilityUploadRequest { BucketName = this._awsBuckeName, Key = keyName, FilePath = filePath, CannedACL = S3CannedACL.Private, StorageClass = S3StorageClass.ReducedRedundancy, PartSize = CalculatePartSize(fileLength), }; uploadRequest.UploadProgressEvent += new EventHandler <UploadProgressArgs>( (object sender, UploadProgressArgs e) => { // Process event. //logger.Debug("PROGRESS {0} -> {1}", filePath, e.ToString()); long delta = e.TransferredBytes - reusedProgressArgs.TransferredBytes; // Report progress. if (UploadProgressed != null) { UploadProgressed(reusedProgressArgs, () => { reusedProgressArgs.State = TransferState.TRANSFERRING; reusedProgressArgs.DeltaTransferredBytes = delta; reusedProgressArgs.TransferredBytes = e.TransferredBytes; }); } }); // Report start - before any possible failures. if (UploadStarted != null) { UploadStarted(reusedProgressArgs, () => { reusedProgressArgs.State = TransferState.STARTED; }); } // TODO(jweyrich): Make it interruptible - use UploadAsync? fileTransferUtility.Upload(uploadRequest); // Report completion. if (UploadCompleted != null) { UploadCompleted(reusedProgressArgs, () => { reusedProgressArgs.State = TransferState.COMPLETED; }); } } catch (OperationCanceledException exception) { logger.Info("Upload canceled: {0}", filePath); // Report cancelation. if (UploadCanceled != null) { UploadCanceled(reusedProgressArgs, () => { reusedProgressArgs.Exception = exception; reusedProgressArgs.State = TransferState.CANCELED; }); } } catch (Exception exception) { if (exception is AmazonS3Exception) { AmazonS3Exception amznException = exception as AmazonS3Exception; if (amznException.ErrorCode != null && (amznException.ErrorCode.Equals("InvalidAccessKeyId") || amznException.ErrorCode.Equals("InvalidSecurity"))) { logger.Log(LogLevel.Warn, "Check the provided AWS Credentials."); } else { logger.Log(LogLevel.Warn, "Error occurred during the upload of {0}\nMessage:'{1}'", filePath, amznException.Message); } } else { logger.Log(LogLevel.Warn, "Exception occurred during the upload of {0}\nException: {1}", filePath, exception.Message); } // Report failure. if (UploadFailed != null) { UploadFailed(reusedProgressArgs, () => { reusedProgressArgs.State = TransferState.FAILED; reusedProgressArgs.Exception = exception; }); } } finally { if (fileTransferUtility != null) { fileTransferUtility.Dispose(); } } }
public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3, string s3ServiceUrl, string awsaccess, string awssecret, out string info, out string fullBucket) { info = string.Empty; fullBucket = string.Empty; AmazonS3Config config = new AmazonS3Config(); config.ServiceURL = s3ServiceUrl; RegionEndpoint regionEndpoint = RegionEndpoint.USEast1; IAmazonS3 client = new AmazonS3Client(awsaccess, awssecret, regionEndpoint); TransferUtility utility = new TransferUtility(client); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); try { if (string.IsNullOrWhiteSpace(subDirectoryInBucket)) { request.BucketName = bucketName; } else { if (!bucketName.EndsWith("/")) { bucketName += "/"; } request.BucketName = bucketName + subDirectoryInBucket; } if (request.BucketName.EndsWith("/")) { request.BucketName = request.BucketName.Substring(0, request.BucketName.Length - 1); } request.Key = fileNameInS3; request.FilePath = localFilePath; request.StorageClass = S3StorageClass.Standard; request.CannedACL = S3CannedACL.PublicRead; request.AutoCloseStream = true; try { utility.Upload(request); } catch (Exception e) { throw new Exception(fileNameInS3 + "\n" + e.ToString()); } info = request.Key + Environment.NewLine + request.FilePath + Environment.NewLine + request.BucketName; IEnumerator keys = request.Metadata.Keys.GetEnumerator(); for (int x = 0; x < request.Metadata.Keys.Count; x++) { info += request.Metadata[keys.Current.ToString()]; keys.MoveNext(); } fullBucket = request.BucketName + "/" + fileNameInS3; } catch (Exception e) { return(false); } finally { utility.Dispose(); client.Dispose(); config = null; request = null; } return(true); }
public static void Dispose() { transferUtility.Dispose(); s3Client.Dispose(); initialized = false; }
public ActionResult Create(Event imageDB) { // Upload event image path to database// string filename = Path.GetFileNameWithoutExtension(imageDB.ImageFile.FileName); string extension = Path.GetExtension(imageDB.ImageFile.FileName); filename = filename + DateTime.Now.ToString("yymmssfff") + extension; string keyName = filename; string aws_s2 = "https://tech-events-uk.s3.eu-west-2.amazonaws.com/".ToString(); imageDB.ImagePath = aws_s2 + filename; //Upload image to AWS S3 ------------// HttpPostedFileBase file = Request.Files[0]; var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion); var fileTransferUtility = new TransferUtility(s3Client); var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName, InputStream = file.InputStream, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = keyName, CannedACL = S3CannedACL.PublicRead }; fileTransferUtilityRequest.Metadata.Add("param1", "Value1"); fileTransferUtilityRequest.Metadata.Add("param2", "Value2"); fileTransferUtility.Upload(fileTransferUtilityRequest); fileTransferUtility.Dispose(); //Coverts postcode to latitude and longitude and upload to database// string requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", Uri.EscapeDataString(imageDB.Postcode), "AIzaSyBj8k95-RJyz0HNan_RcgS_-suLQVb7NzA"); WebRequest request = WebRequest.Create(requestUri); WebResponse response = request.GetResponse(); XDocument xdoc = XDocument.Load(response.GetResponseStream()); XElement result = xdoc.Element("GeocodeResponse").Element("result"); XElement locationElement = result.Element("geometry").Element("location"); XElement lat = locationElement.Element("lat"); XElement lng = locationElement.Element("lng"); imageDB.Latitude = Convert.ToDouble(lat.Value); imageDB.Longitude = Convert.ToDouble(lng.Value); { db.Event.Add(imageDB); db.SaveChanges(); return(RedirectToAction("Index")); } }
public void Dispose() { s3?.Dispose(); }