public bool SaveTo(IFormFile file, string relativeFilePath) { try { TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketName, InputStream = file.OpenReadStream(), StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = file.Length, Key = relativeFilePath, CannedACL = S3CannedACL.PublicRead, }; fileTransferUtilityRequest.Metadata.Add("param1", "Value1"); fileTransferUtilityRequest.Metadata.Add("param2", "Value2"); fileTransferUtility.Upload(fileTransferUtilityRequest); log.Information("Upload file to s3 bucket, file path -> " + relativeFilePath); return(true); } catch (AmazonS3Exception e) { log.Error("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { log.Error("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } return(false); }
public void StoreCalculation(string id, MatrixCalculation calculation) { var memoryStream = new MemoryStream(); serializer.Serialize(calculation, memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); transferUtility.Upload(memoryStream, bucketName, id); }
private void uploadevent() { string filePath = @"c:\logKeyPress.csv"; string existingBucketName = "capf17g5"; //Created manually var accessKey = "AKIAIGBVXNNLMB4OPC6A"; var secretKey = "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"; try { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1)); /* Upload the file(file name is taken as the object key name). */ try { pBarUploadStatus.Value = 25; fileTransferUtility.Upload(filePath, existingBucketName); } catch { MessageBox.Show("File not found"); pBarUploadStatus.Value = 10; lblStatus.Text = "Status: Idle"; } pBarUploadStatus.Value = 50; /* Set the file storage class and the sharing type*/ TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = existingBucketName, FilePath = filePath, StorageClass = S3StorageClass.Standard, CannedACL = S3CannedACL.PublicReadWrite, ContentType = "text/csv", //video/x-mp4 (MMIE type for video) }; try { pBarUploadStatus.Value = 75; fileTransferUtility.Upload(fileTransferUtilityRequest); lblStatus.Text = "Status: UPLOADED"; pBarUploadStatus.Value = 100; } catch { lblStatus.Text = "Failed to upload the file"; pBarUploadStatus.Value = 10; } } catch (AmazonS3Exception) { lblStatus.Text = "Failed to upload the file"; pBarUploadStatus.Value = 10; } }
[ExcludeFromCodeCoverage] //Test method below public void UploadButton_Click(object sender, EventArgs e) { TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); request.BucketName = "eecs393minesweeper"; String filename = YourMapsList.SelectedItem.ToString(); request.FilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper\\" + filename + ".map"; utility.Upload(request); ReadOnlineFiles(); PopulateOnlineList(); }
public void SaveDataFile(byte[] data, bool branch, int toFileVersion, String stationName) { using (IAmazonS3 s3Client = CreateS3Client()) { TransferUtility fileTransferUtility = new TransferUtility(s3Client); if (branch) { //upload a branched copy, but do not update the main version var newFileName = AddPreSuffixToFileName($"{stationName}_{toFileVersion.ToString().PadLeft(4, '0')}", _dataFileName); var fileKey = $"{_secretsDirectory}/{newFileName}"; using (var ms = new MemoryStream(data)) { fileTransferUtility.Upload(ms, _bucketName, fileKey); } } else { //copy the current main to a new name propertyValue as a suffix then //upload a new copy var fileKey = $"{_secretsDirectory}/{_dataFileName}"; var response = s3Client.GetObjectMetadata(new GetObjectMetadataRequest() { BucketName = _bucketName, Key = fileKey }); var existingVersion = response.Metadata[$"x-amz-meta-{VersionIdPropertyName.ToLower()}"]; var oldFileKey = $"{_secretsDirectory}.old/{_dataFileName}.{existingVersion}"; s3Client.CopyObject(new CopyObjectRequest() { SourceBucket = _bucketName, DestinationBucket = _bucketName, SourceKey = fileKey, DestinationKey = oldFileKey }); using (var ms = new MemoryStream(data)) { var uploadRequest = new TransferUtilityUploadRequest() { BucketName = _bucketName, Key = fileKey, InputStream = ms }; uploadRequest.Metadata[VersionIdPropertyName] = toFileVersion.ToString(); fileTransferUtility.Upload(uploadRequest); } } } }
public void TestSingleUploads() { // Test simple PutObject upload var key = "contentBodyPut" + random.Next(); PutObjectRequest putObjectRequest = new PutObjectRequest() { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; SetMetadataAndHeaders(putObjectRequest); Client.PutObject(putObjectRequest); ValidateObjectMetadataAndHeaders(key); using (var tu = new TransferUtility(Client)) { // Test small TransferUtility upload key = "transferUtilitySmall" + random.Next(); UtilityMethods.GenerateFile(tempFile, smallFileSize); var smallRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = key, FilePath = tempFile }; SetMetadataAndHeaders(smallRequest); tu.Upload(smallRequest); ValidateObjectMetadataAndHeaders(key); // Test large TransferUtility upload // disable clock skew testing, this is a multithreaded operation using (RetryUtilities.DisableClockSkewCorrection()) { key = "transferUtilityLarge" + random.Next(); UtilityMethods.GenerateFile(tempFile, largeFileSize); var largeRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = key, FilePath = tempFile }; SetMetadataAndHeaders(largeRequest); tu.Upload(largeRequest); ValidateObjectMetadataAndHeaders(key); } } }
private bool Upload(Stream stream, string fileKey, bool asPublic = false, bool closeStream = false) { try { var request = new TransferUtilityUploadRequest() { BucketName = _amazonS3StorageConfiguration.AWSFileBucket, Key = fileKey, InputStream = stream, AutoCloseStream = closeStream, AutoResetStreamPosition = true, }; if (asPublic) { request.CannedACL = S3CannedACL.PublicRead; } _transferUtility.Upload(request); if (stream.CanSeek) { stream.Seek(0, SeekOrigin.Begin); } } catch { return(false); } return(true); }
public void TestMultipartUploadFileViaTransferUtility() { var transferConfig = new TransferUtilityConfig { MinSizeBeforePartUpload = 6000000 }; var transfer = new TransferUtility(Client, transferConfig); var content = new string('a', 7000000); var key = UtilityMethods.GenerateName(nameof(ObjectLockConfigurationTests)); var filePath = Path.Combine(Path.GetTempPath(), key + ".txt"); // Create the file using (StreamWriter writer = File.CreateText(filePath)) { writer.Write(content); } var uploadRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = key, CalculateContentMD5Header = true, FilePath = filePath }; transfer.Upload(uploadRequest); using (var getResponse = Client.GetObject(bucketName, uploadRequest.Key)) { var getBody = new StreamReader(getResponse.ResponseStream).ReadToEnd(); Assert.AreEqual(content, getBody); } }
public void TestMultipartUploadStreamViaTransferUtility() { var transferConfig = new TransferUtilityConfig { MinSizeBeforePartUpload = 6000000 }; var transfer = new TransferUtility(Client, transferConfig); var content = new string('a', 7000000); var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); var uploadRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = UtilityMethods.GenerateName(nameof(ObjectLockConfigurationTests)), CalculateContentMD5Header = true, InputStream = contentStream }; transfer.Upload(uploadRequest); using (var getResponse = Client.GetObject(bucketName, uploadRequest.Key)) { var getBody = new StreamReader(getResponse.ResponseStream).ReadToEnd(); Assert.AreEqual(content, getBody); } }
/// <summary> /// To upload object to AWS S3 Bucket /// </summary> /// <param name="transactionType"></param> /// <param name="currentClientId"></param> /// <param name="imageName"></param> /// <param name="imagePath"></param> /// <param name="keyName"></param> /// <returns></returns> public int UploadImagesToS3ByTransferUtil(string transactionType, int currentClientId, string imageName, string imagePath, string keyName, Stream file) { try { using (var client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, Amazon.RegionEndpoint.EUWest2)) // using (var client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2)) { string objectKey = AppSettingsUtil.GetPathForKeyNameBucket(transactionType, currentClientId); objectKey = objectKey + "/" + keyName; using (var transferUtility = new TransferUtility(client)) { //Creates PutObjectRequest of AmazonS3 var transferUtilityUploadRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = objectKey, InputStream = file }; //Adds an object to a bucket transferUtility.Upload(transferUtilityUploadRequest); MakeImagePublicReadOnly(objectKey); File.Delete(imagePath); return(currentClientId); } } } catch (Exception ex) { Program.ErrorLogging(ex); return(0); } }
private ImageDataDto UploadImageToAws(IFormFile file) { string fileType = Path.GetExtension(file.FileName.ToLower()).Replace(".", ""); TransferUtility fileTransferUtility = new TransferUtility(s3Client); var fileStream = file.OpenReadStream(); TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = Environment.GetEnvironmentVariable("AWS_BUCKET_NAME"), Key = $"{Guid.NewGuid().ToString()}.{fileType}", InputStream = fileStream, AutoCloseStream = false, ContentType = $"image/{fileType}", CannedACL = S3CannedACL.PublicRead }; fileTransferUtility.Upload(fileTransferUtilityRequest); Image image = Image.FromStream(fileStream); fileStream.Close(); return(new ImageDataDto { Src = $"https://{fileTransferUtilityRequest.BucketName}.s3.amazonaws.com/{fileTransferUtilityRequest.Key}", Type = fileType, Width = image.Width, Height = image.Height }); }
private static Boolean MoveFile(string saveAsFileName, string wkBaseFolder, Int32 wkVersionNo, string currentFilePath) { try { string destFile = wkBaseFolder + "/" + wkVersionNo.ToString() + "/" + saveAsFileName; AmazonS3Config config = new AmazonS3Config(); config.ServiceURL = AWSHelpers.GetS3EndPoint(); using (var client = AWSClientFactory.CreateAmazonS3Client(AWSHelpers.GetAccesskey(), AWSHelpers.GetSecretkey(), config)) { TransferUtility s3TransferUtil = new TransferUtility(client); TransferUtilityUploadRequest s3TrfrReq = new TransferUtilityUploadRequest(); s3TrfrReq.CannedACL = Amazon.S3.Model.S3CannedACL.BucketOwnerFullControl; s3TrfrReq.FilePath = currentFilePath; s3TrfrReq.BucketName = AWSHelpers.GetBucketname(); s3TrfrReq.Key = destFile; s3TransferUtil.Upload(s3TrfrReq); // Delete the temporary PDF on the web server FileInfo TheFile = new FileInfo(s3TrfrReq.FilePath); if (TheFile.Exists) { // File found so delete it. TheFile.Delete(); } } return(true); } catch (Exception ex) { return(false); } }
private string Upload2S3(byte[] pdf) { var bucketName = "logs.huge.head.li"; using (var client = new AmazonS3Client()) { var key = $"P-{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff")}.pdf"; using (var newMemoryStream = new System.IO.MemoryStream(pdf)) { var uploadRequest = new TransferUtilityUploadRequest { InputStream = newMemoryStream, Key = key, BucketName = bucketName }; var util = new TransferUtility(client); util.Upload(uploadRequest); } var preSignedUrlRequest = new GetPreSignedUrlRequest { BucketName = bucketName, Key = key, Expires = DateTime.UtcNow.AddMinutes(5) }; var url = client.GetPreSignedURL(preSignedUrlRequest); return(url); } }
public static void UploadToS3(IAmazonS3 s3Client, string bucketName, string key, Stream stream) { Console.WriteLine("UploadToS3 entered." + stream.Length); string signedUrl = string.Empty; try { var uploadRequest = new TransferUtilityUploadRequest { InputStream = stream, BucketName = bucketName, CannedACL = S3CannedACL.AuthenticatedRead, Key = key }; // File upload to S3 TransferUtility fileTransferUtility = new TransferUtility(s3Client); fileTransferUtility.Upload(uploadRequest); Console.WriteLine("Upload completed"); } catch (AmazonS3Exception s3Exception) { Console.WriteLine(s3Exception.Message, s3Exception.InnerException); } }
public override IEnumerable <PvcStream> Execute(IEnumerable <PvcStream> inputStreams) { var filteredInputStreams = FilterUploadedFiles(inputStreams); var transfer = new TransferUtility(this.s3client); foreach (var inputStream in filteredInputStreams) { if (inputStream.StreamName == null || inputStream.StreamName.Length == 0) { continue; } var uploadReq = new TransferUtilityUploadRequest(); uploadReq.BucketName = this.bucketName; uploadReq.InputStream = inputStream; uploadReq.Key = this.StreamNameToKey(inputStream.StreamName); uploadReq.Headers.ContentMD5 = this.keyMD5Sums[uploadReq.Key]; uploadReq.Headers.ContentType = MimeMapping.GetMimeMapping(inputStream.StreamName); if (inputStream.Tags.Contains("gzip")) { uploadReq.Headers.ContentEncoding = "gzip"; } transfer.Upload(uploadReq); } ; return(inputStreams); }
public void UploadImage(Vehicle vehicle, IFormFile file) { //string bucketName = _config.GetSection("AWS").GetValue<string>("bucketName"); //string awsAccessKeyId = _config.GetSection("AWS").GetValue<string>("accessKeyId"); //string awsSecretAccessKey = _config.GetSection("AWS").GetValue<string>("secretAccessKey"); string bucketName = "trans-track-images"; string awsAccessKeyId = "AKIA52EKHXRHDXJ72DUG"; string awsSecretAccessKey = "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"; string keyName = vehicle.License + ".jpg"; string imageBasePath = "https://trans-track-images.s3-us-west-2.amazonaws.com"; if (file != null && file.Length > 0) { using (var client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.USWest2)) { using (var newMemoryStream = new MemoryStream()) { file.CopyTo(newMemoryStream); var uploadRequest = new TransferUtilityUploadRequest { InputStream = newMemoryStream, Key = keyName, BucketName = bucketName, CannedACL = S3CannedACL.PublicRead }; var fileTransferUtility = new TransferUtility(client); fileTransferUtility.Upload(uploadRequest); } vehicle.ImagePath = imageBasePath + "/" + keyName; } } }
public void UploadFile(string remoteFilename, string localFilename, Dictionary <string, string> metadata = null) { if (remoteFilename[0] == '/') { remoteFilename = remoteFilename.Substring(1); } TransferUtilityUploadRequest uploadRequest = new TransferUtilityUploadRequest { BucketName = CurrentBucketName, FilePath = localFilename, Key = remoteFilename, AutoCloseStream = true }; if (metadata != null) { foreach (var kvp in metadata) { uploadRequest.Metadata.Add(kvp.Key, kvp.Value); } } uploadRequest.UploadProgressEvent += (sender, e) => { if (FileProgressChanged != null) { FileProgressChanged(e.FilePath, e.TransferredBytes, e.TotalBytes, e.PercentDone); } }; _transfer.Upload(uploadRequest); }
public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3) { // input explained : // localFilePath = the full local file path e.g. "c:\mydir\mysubdir\myfilename.zip" // bucketName : the name of the bucket in S3 ,the bucket should be alreadt created // subDirectoryInBucket : if this string is not empty the file will be uploaded to // a subdirectory with this name // fileNameInS3 = the file name in the S3 // create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1 // you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1 // SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not // store your file in a different cloud storage but (i think) it differ in performance // depending on your location IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.EUWest1); // create a TransferUtility instance passing it the IAmazonS3 created in the first step TransferUtility utility = new TransferUtility(client); // making a TransferUtilityUploadRequest instance TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); if (subDirectoryInBucket == "" || subDirectoryInBucket == null) { request.BucketName = bucketName; //no subdirectory just bucket name } else { // subdirectory and bucket name request.BucketName = bucketName + @"/" + subDirectoryInBucket; } request.Key = fileNameInS3; //file name up in S3 request.FilePath = localFilePath; //local file name utility.Upload(request); //commensing the transfer return(true); //indicate that the file was sent }
public void UploadFile() { //Dosya yükleme //var transferUtility = new TransferUtility(client); //transferUtility.Upload( // AppDomain.CurrentDomain.BaseDirectory + "\\test.txt", bucketName); //Console.WriteLine("başarılı, yüklendi dosya"); //klasör upload etme //var transferUtility = new TransferUtility(client); //transferUtility.UploadDirectory( // AppDomain.CurrentDomain.BaseDirectory + "\\example", bucketName); //Console.WriteLine("başarılı, yüklendi klasör"); //Console.ReadLine(); //İzin isteme gönderilen dosya için var transferUtility = new TransferUtility(client); var transferForRequest = new TransferUtilityUploadRequest { FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\test.txt", CannedACL = S3CannedACL.PublicRead, BucketName = bucketName }; transferUtility.Upload(transferForRequest); Console.WriteLine("başarılı, "); Console.ReadLine(); }
static void UploadFile(FileInfo file) { var key = file.Directory.FullName.TrimStart(UploadAndDeleteSource.FullName) .TrimStart("\\").TrimEnd("\\").WithSuffix("/"); if (KeepExtension) { key += file.Name; } else { key += file.NameWithoutExtension(); } if (Args.Contains("/lowercase")) { key = key.ToLower(); } else if (Args.Contains("/uppercase")) { key = key.ToUpper(); } Console.WriteLine("Moving key:" + key + " file:" + file.FullName.TrimStart(UploadAndDeleteSource.FullName) + "..."); Util.Upload(file.FullName, Param("bucket"), key); file.Delete(); }
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 string PostSoundFile() { HttpPostedFileBase file = Request.Files[fileUpload]; Stream receiveStream = file.InputStream; // basic params try { // initialize our client IAmazonS3 client = new AmazonS3Client(ConfigurationManager.AppSettings["AmazonAccessKey"], ConfigurationManager.AppSettings["AmazonSecretAccessKey"], RegionEndpoint.EUWest1); using (var transferUtility = new TransferUtility(client)) { var request = new TransferUtilityUploadRequest { BucketName = ConfigurationManager.AppSettings["AmazonBucketName"], Key = keyName, InputStream = receiveStream }; transferUtility.Upload(request); } } catch (Exception e) { } string transcriptURL = GetTranscriptURL(); string result = GetTranscript(transcriptURL); return(result); }
public string Upload(string storageBasePath, string localPath, Guid userId) { String key = String.Empty; if (String.IsNullOrEmpty(storageBasePath)) { key = "backup/" + Path.GetFileName(localPath); } else { key = String.Concat(storageBasePath.Trim(new char[] { ' ', '/', '\\' }), "/", Path.GetFileName(localPath)); } using (var fileTransferUtility = new TransferUtility(accessKeyId, secretAccessKey, RegionEndpoint.GetBySystemName(region))) { fileTransferUtility.Upload( new TransferUtilityUploadRequest { BucketName = bucket, FilePath = localPath, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB. Key = key }); } return(key); }
public void UploadToS3(S3File file) { if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null) { throw new Exception("S3 File is NULL or has some NULL attributes"); } if (Credentials is null || Credentials.AWS_AccessKey is null || Credentials.AWS_SecretKey is null || Credentials.Region is null) { throw new CredentialsNotProvidedException(); } try { TransferUtility fileTransferUtility = new TransferUtility(getS3Client(Credentials)); TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = file.Bucket, FilePath = file.LocalFilePath, Key = file.RemoteFilePath, }; fileTransferUtility.Upload(fileTransferUtilityRequest); } catch (Exception ex) { throw ex; } }
// SendFileToS3() public void SendFileToS3(Stream FileStream, string FileName, string IdSwitch) { var client = con.S3_GetClient(); var BucketName = "bostonscientific"; var SubDirectory = "Files"; try { TransferUtility utility = new TransferUtility(client); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); request.BucketName = BucketName + @"/" + SubDirectory; request.Key = FileName; request.InputStream = FileStream; request.CannedACL = S3CannedACL.PublicRead; utility.Upload(request); var NewFile = _tools.Encrypt(string.Format("https://s3-us-west-2.amazonaws.com/bostonscientific/Files/{0}", FileName)); FileName = _tools.Encrypt(FileName); AddFile(IdSwitch, NewFile, FileName); } catch (Exception ex) { Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> SendFileToS3(). \nDescripción: " + ex.Message); } }
public void TestSimpleUploadFileFailViaTransferUtility() { var transferConfig = new TransferUtilityConfig { MinSizeBeforePartUpload = 6000000 }; var transfer = new TransferUtility(Client, transferConfig); var content = new string('a', 2000000); var key = UtilityMethods.GenerateName(nameof(ObjectLockConfigurationTests)); var filePath = Path.Combine(Path.GetTempPath(), key + ".txt"); // Create the file using (StreamWriter writer = File.CreateText(filePath)) { writer.Write(content); } // Do not set CalculateContentMD5Header as true which should cause upload to fail. var uploadRequest = new TransferUtilityUploadRequest { BucketName = bucketName, Key = key, FilePath = filePath }; transfer.Upload(uploadRequest); }
public SendStatus UploadFile(FileSendInfo lstFileinfo) { SendStatus result = SendStatus.Complete; try { FileInfo file = new FileInfo(lstFileinfo.FileFullPath); if (file.Exists == false) { Debug.Assert(false, "파일이 존재하지 않습니다 : " + lstFileinfo.FileFullPath); result = SendStatus.Fail; } string strFilePath = "IH" + DateTime.Now.ToString("yyyyMMddHHmmssfff00") + file.Extension; fileTransferUtility.Upload(lstFileinfo.FileFullPath, bucketName, strFilePath); Console.WriteLine("Upload Complete : " + lstFileinfo.FileFullPath); log.Debug("Upload Complete : " + lstFileinfo.FileFullPath + " / " + strFilePath); } catch (AmazonS3Exception e) { Debug.Assert(false, e.Message); log.Error(string.Format("Error encountered on server. Message:'{0}' when writing an object", e.Message)); result = SendStatus.Fail; } catch (Exception e) { Debug.Assert(false, e.Message); log.Error(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message)); result = SendStatus.Fail; } return(result); }
public static bool sendMyFileToS3(HttpPostedFileBase file, string fileNameInS3) { try { var S3Config = new AmazonS3Config { RegionEndpoint = RegionEndpoint.USEast1, //its default rekeygion set by amazon }; IAmazonS3 client = new AmazonS3Client(AppConfig.AWSAccessKey, AppConfig.AWSSecretKey, S3Config); TransferUtility utility = new TransferUtility(client); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest(); request.BucketName = AppConfig.AWSProfileName + @"/ProfilePics"; request.Key = fileNameInS3; //file name up in S3 request.InputStream = file.InputStream; request.ContentType = file.ContentType; request.FilePath = Path.GetFileName(file.FileName); utility.Upload(request); //commensing the transfer } catch (Exception ex) { throw; } return(true); //indicate that the file was sent }
private static void UploadS3Archive(Settings settings, string zipPath) { var transferUtility = new TransferUtility( settings.AWSAccessKeyID, settings.AWSSecretAccessKey, RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName)); // Create bucket if not found if (!transferUtility.S3Client.DoesS3BucketExist(settings.AWSS3Bucket)) { transferUtility.S3Client.PutBucket( new PutBucketRequest() { BucketName = settings.AWSS3Bucket }); } try { // Copy zipfile var request = new TransferUtilityUploadRequest { BucketName = settings.AWSS3Bucket, FilePath = zipPath, //StorageClass // TODO }; request.UploadProgressEvent += Request_UploadProgressEvent; transferUtility.Upload(request); } catch (Exception ex) { throw ex; } }
/// <summary> /// Uploads a file to S3. This method uses the "TransferUtility" class in order to upload the file. /// </summary> public bool FileUpload(string bucketname, string dataname, string filepath, S3StorageClass storageClass, S3CannedACL s3CannedACL) { // Reset error info ClearErrorInfo(); // Save data try { TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = bucketname, FilePath = filepath, StorageClass = storageClass, PartSize = 6291456, // 6 MB. Key = dataname, ContentType = "binary/octet-stream", CannedACL = s3CannedACL }; fileTransferUtility.Upload(fileTransferUtilityRequest); } catch (Exception ex) { ErrorCode = e_Exception; ErrorMessage = ex.Message + "::" + ex.InnerException; } return(ErrorCode == 0); }