I need to get file url after upload the file to amazons3 server.
Here is my upload code.
How to return amazons3 path ?
public static bool UploadToS3(string bucketName, string bucketFilePath, Byte[] localPath)
{
var client = Amazon.AWSClientFactory.CreateAmazonS3Client(Config.EmailServer.AwsAccessKey, Config.EmailServer.AwsSecretKey, Amazon.RegionEndpoint.EUWest1);
PutObjectRequest request = new PutObjectRequest()
{
BucketName = bucketName,
Key = bucketFilePath,
InputStream = new MemoryStream(localPath),
AutoCloseStream = true,
CannedACL = S3CannedACL.PublicRead,
StorageClass = S3StorageClass.ReducedRedundancy
};
PutObjectResponse response = client.PutObject(request);
return true;
}
Simply you can generate download expiry link after upload completed.
example:
var expiryUrlRequest = new GetPreSignedUrlRequest()
.WithBucketName(BucketName)
.WithKey(Key)
.WithExpires(DateTime.Now.AddDays(10));
string url = _amazonS3Client.GetPreSignedURL(expiryUrlRequest);
Try this method
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest();
request.BucketName = "my-bucket-name";
request.Key = "secret_plans.txt";
request.Expires = DateTime.Now.AddHours(1);
request.Protocol = Protocol.HTTP;
string url = client.GetPreSignedURL(request);
Console.WriteLine(url);
Related
I am trying to delete a file in S3 using C# code:
string _bucketName = "mybucket-ap-southeast-1-123627123717";
string _filename "ronaldo.png";
AmazonS3Config _config = new AmazonS3Config();
_config.ServiceURL = HOSTNAME + _bucketName;
IAmazonS3 _client = new AmazonS3Client(ACCESS_KEY, ACCESS_SECRET, _config);
await _client.DeleteObjectAsync(
new Amazon.S3.Model.DeleteObjectRequest { BucketName = _bucketName, Key = _fileName });
The code does not throw any exception or error, but when I check and refresh the AWS S3 Management console the file is still there! What have I missed?
IAmazonS3 s3Client = new AmazonS3Client(_appConfiguration["AWS:AccessKey"], _appConfiguration["AWS:SecretKey"], RegionEndpoint.USEast1);
var deleteObjectRequest = new DeleteObjectRequest { BucketName = "BucketName ", Key = "key"};
s3Client.DeleteObjectAsync(deleteObjectRequest).Wait();
IAmazonS3 _client1 = new AmazonS3Client(AwsAccessKeyId, AwsSecretKey, RegionEndpoint.APSouth1);
var deleteRequest = new DeleteObjectRequest
{
Key = YourFolderName/YourFileName,
BucketName = YourBucketName,
};
await _client1.DeleteObjectAsync(deleteRequest);
Use this its working fine
So Im trying to upload a zip file to s3 for storage. But I keep getting 403 forbidden back.
My code works when i upload an image file but not when i upload a zip file
My code:
internal static void UploadFiletoS3fromZip(Byte[] fileByteArray, string fileName, string bucketName, string filepath)
{
try
{
CognitoAWSCredentials credentials = new CognitoAWSCredentials("###PVTCredentials###", Amazon.RegionEndpoint.EUWest1);
client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.EUWest1);
using (MemoryStream fileToUpload = new MemoryStream(fileByteArray))
{
PutObjectRequest request = new PutObjectRequest()
{
BucketName = bucketName,
Key = fileName,
InputStream = fileToUpload,
ContentType = "application/zip"
};
request.Timeout = TimeSpan.FromSeconds(60);
PutObjectResponse response2 = client.PutObject(request);
}
}
catch (AmazonS3Exception s3Exception)
{
s3Exception.ToExceptionless().Submit();
}
catch (Exception ex)
{
ex.ToExceptionless().Submit();
}
}
Can anyone see what the problem here is? i get a 403 forbidden in the s3Exception. the credentials im using does have write permission and works perfectly when i use a base64 image and change the contentType to "image/jpeg"
OK SO I FOUND THE FIX....
instead of using
CognitoAWSCredentials credentials = new CognitoAWSCredentials("###PVTCredentials###", Amazon.RegionEndpoint.EUWest1);
client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.EUWest1);
i replaced it with
var client = new AmazonS3Client(AwsAccessKeyId,AwsSecretAccessKey, Amazon.RegionEndpoint.EUWest1);
For if anyone else is having this issue, replace CognitoAWSCredentials with id and secret credentials
using (var client = new AmazonS3Client(LlaveAcceso, LlaveAccesoSecreta, RegionEndpoint.USEast2))
{
using (var newMemoryStream = new MemoryStream())
{
var putArchivo = new PutObjectRequest
{
BucketName = Buquet,
Key = file.FileName,
FilePath = ruta,
};
PutObjectResponse response = client.PutObjectAsync(putArchivo).Result;
MessageBox.Show("Archivo " + file.FileName + " Cargado Correctamente.", "AWS Loader", MessageBoxButtons.OK, MessageBoxIcon.Information);
label2.Text = "";
}
}
I have next error:
"The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256."
When I try download a file from my bucket on Amazon S3. My code is the next:
AmazonS3Config config = new AmazonS3Config();
config.CommunicationProtocol = Protocol.HTTP;
config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
AmazonS3Client s3Client = new AmazonS3Client("MyAccesKeyAWS", "MyAccesSecretAWS", config);
TransferUtility transfer = new TransferUtility(s3Client);
TransferUtilityDownloadRequest downloader = new TransferUtilityDownloadRequest();
downloader.BucketName = "bucketName";
downloader.FilePath = "MyPath\\To\\Local\\File\\";
downloader.Key = "NameFile.pdf";
transfer.Download(downloader); //<-- here the ERROR:
this generete the next error: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.
I was reasearch it on google and on some blogs.
some suggest using the property "signature version" to v4.
something like...
config.signatureVersion = "v4";
but my config object, not have this property.
any suggestion?
thank you!!!
Try This Code
AmazonS3Config config = new AmazonS3Config();
string accessKey = WebConfigurationManager.AppSettings["AWSaccessKey"].ToString();
string secretKey = WebConfigurationManager.AppSettings["AWSsecretKey"].ToString();
config.ServiceURL = WebConfigurationManager.AppSettings["AWSServiceURL"].ToString();
string storageContainer = WebConfigurationManager.AppSettings["AWSBucketName"].ToString();
AmazonS3Client client2 = new AmazonS3Client(
accessKey,
secretKey,
config
);
Amazon.S3.AmazonS3 client3 = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey, config);
GetObjectRequest request1 = new GetObjectRequest();
request1.BucketName = storageContainer;
request1.WithBucketName(storageContainer);
request1.WithKey(originalfileName);
GetObjectResponse response1 = client3.GetObject(request1);
using (Stream responseStream = response1.ResponseStream)
{
var bytes = ReadStream(responseStream);
var download = new FileContentResult(bytes, "application/pdf");
download.FileDownloadName = response1.Key;
int c = filePath.Split('/').Length;
byte[] fileBytes = download.FileContents;
//return download;
var fileEntry = new ZipEntry(filePath.Split('/')[c - 1].ToString());
zipStream.PutNextEntry(fileEntry);
zipStream.Write(fileBytes, 0, fileBytes.Length);
}
zipStream.Flush();
zipStream.Close();
I try upload file in amazon s3, but always return this message.
My code:
AmazonS3Config S3Config = new AmazonS3Config()
{
ServiceURL = "s3.amazonaws.com",
CommunicationProtocol = Protocol.HTTP,
RegionEndpoint = RegionEndpoint.SAEast1
};
using (AmazonS3Client client = new AmazonS3Client(KEY_S3, PASSWORD, S3Config))
{
string pathInS3 = folder + "/" + fileName;
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(pathInS3);
request.WithInputStream(memoryStreamFile);
request.CannedACL = S3CannedACL.PublicReadWrite;
client.PutObject(request);
}
I had use lock in request and client but do not resolve.
I think the problem is the memoryStreamFile, please do double check trying to read the content of your memorystreamFile.So another way to upload files to AmazonS3 with C# is the following:
AmazonS3Config cfg = new AmazonS3Config();
cfg.RegionEndpoint = Amazon.RegionEndpoint.EUCentral1;// region endpoint
string bucketName = "your bucket";
AmazonS3Client s3Client = new AmazonS3Client("your access key", "your secret key", cfg);
string dataString ="your data ";
MemoryStream data = new System.IO.MemoryStream(UTF8Encoding.ASCII.GetBytes(dataString));
TransferUtility t = new TransferUtility(s3Client);
t.Upload(data, bucketName, "testUploadFromTransferUtility.txt");
I have been trying to upload file to AWS S3 , below is the code that I am trying
private static void UploadToAWS(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
string accessKey = ConfigurationManager.AppSettings["AMAZON_S3_ACCESSKEY"].ToString();
string secretKey = ConfigurationManager.AppSettings["AMAZON_S3_SECRETKEY"].ToString();
AmazonS3Config asConfig = new AmazonS3Config()
{
ServiceURL = "http://test.s3.amazonaws.com",
};
IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey,secretKey,asConfig);
TransferUtility utility = new TransferUtility(client);
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
request.Headers.CacheControl = "public";
request.Headers.Expires = DateTime.Now.AddYears(3);
request.Headers.ContentEncoding = "gzip";
utility.Upload(request); //commensing the transfer
}
UploadToAWS(#"D:\core_gz.min.js", "test123", "test/build/", "core_gz.min.js");
When I execute this I get the following error
The request signature we calculated does not match the signature you
provided. Check your key and signing method.
Can any one help me here, what am I doing wrong here
I just wanted to post the answer if in case it might help some one else who has the same issue
private static void UploadToAWS(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
string accessKey = ConfigurationManager.AppSettings["AMAZON_S3_ACCESSKEY"].ToString();
string secretKey = ConfigurationManager.AppSettings["AMAZON_S3_SECRETKEY"].ToString();
AmazonS3Config asConfig = new AmazonS3Config()
{
ServiceURL = "http://test.s3.amazonaws.com",
RegionEndpoint = Amazon.RegionEndpoint.APSoutheast1 // this line fixed the issue
};
IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey,secretKey,asConfig);
TransferUtility utility = new TransferUtility(client);
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
request.Headers.CacheControl = "public";
request.Headers.Expires = DateTime.Now.AddYears(3);
request.Headers.ContentEncoding = "gzip";
utility.Upload(request); //commensing the transfer
}
Adding this line in the config fixed my issue
RegionEndpoint = Amazon.RegionEndpoint.APSoutheast1