本文整理汇总了C#中Amazon.S3.AmazonS3Client.PutObject方法的典型用法代码示例。如果您正苦于以下问题:C# AmazonS3Client.PutObject方法的具体用法?C# AmazonS3Client.PutObject怎么用?C# AmazonS3Client.PutObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Amazon.S3.AmazonS3Client
的用法示例。
在下文中一共展示了AmazonS3Client.PutObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendImageToS3
public static Boolean SendImageToS3(String key, Stream imageStream)
{
var success = false;
using (var client = new AmazonS3Client(RegionEndpoint.USWest2))
{
try
{
PutObjectRequest request = new PutObjectRequest()
{
InputStream = imageStream,
BucketName = BucketName,
Key = key
};
client.PutObject(request);
success = true;
}
catch (Exception ex)
{
// swallow everything for now.
}
}
return success;
}
示例2: UploadImage
private static S3File UploadImage(string key, Stream inputStream)
{
var s3Config = new AmazonS3Config() { ServiceURL = "http://" + _s3_bucket_region };
using (var cli = new AmazonS3Client(
_s3_access_key,
_s3_secret_access_key,
s3Config))
{
PutObjectRequest req = new PutObjectRequest()
{
BucketName = _s3_bucket_name,
ContentType = "image/jpg",
InputStream = inputStream,
Key = key,
CannedACL = S3CannedACL.PublicRead
};
var response = cli.PutObject(req);
if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("s3: upload failed.");
}
else
{
return new S3File()
{
Key = key,
Url = HttpUtility.HtmlEncode(
String.Format("http://{0}.{1}/{2}", _s3_bucket_name, _s3_bucket_region, key))
};
}
}
}
示例3: Main
static void Main()
{
// Connect to Amazon S3 service with authentication
BasicAWSCredentials basicCredentials =
new BasicAWSCredentials("AKIAIIYG27E27PLQ6EWQ",
"hr9+5JrS95zA5U9C6OmNji+ZOTR+w3vIXbWr3/td");
AmazonS3Client s3Client = new AmazonS3Client(basicCredentials);
// Display all S3 buckets
ListBucketsResponse buckets = s3Client.ListBuckets();
foreach (var bucket in buckets.Buckets)
{
Console.WriteLine(bucket.BucketName);
}
// Display and download the files in the first S3 bucket
string bucketName = buckets.Buckets[0].BucketName;
Console.WriteLine("Objects in bucket '{0}':", bucketName);
ListObjectsResponse objects =
s3Client.ListObjects(new ListObjectsRequest() { BucketName = bucketName });
foreach (var s3Object in objects.S3Objects)
{
Console.WriteLine("\t{0} ({1})", s3Object.Key, s3Object.Size);
if (s3Object.Size > 0)
{
// We have a file (not a directory) --> download it
GetObjectResponse objData = s3Client.GetObject(
new GetObjectRequest() { BucketName = bucketName, Key = s3Object.Key });
string s3FileName = new FileInfo(s3Object.Key).Name;
SaveStreamToFile(objData.ResponseStream, s3FileName);
}
}
// Create a new directory and upload a file in it
string path = "uploads/new_folder_" + DateTime.Now.Ticks;
string newFileName = "example.txt";
string fullFileName = path + "/" + newFileName;
string fileContents = "This is an example file created through the Amazon S3 API.";
s3Client.PutObject(new PutObjectRequest() {
BucketName = bucketName,
Key = fullFileName,
ContentBody = fileContents}
);
Console.WriteLine("Created a file in Amazon S3: {0}", fullFileName);
// Share the uploaded file and get a download URL
string uploadedFileUrl = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
{
BucketName = bucketName,
Key = fullFileName,
Expires = DateTime.Now.AddYears(5)
});
Console.WriteLine("File download URL: {0}", uploadedFileUrl);
System.Diagnostics.Process.Start(uploadedFileUrl);
}
示例4: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (upload.PostedFile != null && upload.PostedFile.ContentLength > 0 && !string.IsNullOrEmpty(Request["awsid"]) && !string.IsNullOrEmpty(Request["awssecret"]) && !string.IsNullOrEmpty(this.bucket.Text))
{
var name = "s3readersample/" + ImageUploadHelper.Current.GenerateSafeImageName(upload.PostedFile.InputStream, upload.PostedFile.FileName);
var client = new Amazon.S3.AmazonS3Client(Request["awsid"], Request["awssecret"], Amazon.RegionEndpoint.EUWest1);
//For some reason we have to buffer the file in memory to prevent issues... Need to research further
var ms = new MemoryStream();
upload.PostedFile.InputStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
var request = new Amazon.S3.Model.PutObjectRequest() { BucketName = this.bucket.Text, Key = name, InputStream = ms, CannedACL = Amazon.S3.S3CannedACL.PublicRead };
var response = client.PutObject(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
result.Text = "Successfully uploaded " + name + "to bucket " + this.bucket.Text;
}
else
{
result.Text = response.HttpStatusCode.ToString();
}
}
}
示例5: Main
static void Main(string[] args)
{
try
{
var client = new AmazonS3Client();
PutObjectResponse putResponse = client.PutObject(new PutObjectRequest
{
BucketName = BUCKET_NAME,
FilePath = TEST_FILE
});
GetObjectResponse getResponse = client.GetObject(new GetObjectRequest
{
BucketName = BUCKET_NAME,
Key = TEST_FILE
});
getResponse.WriteResponseStreamToFile(@"c:\talk\" + TEST_FILE);
var url = client.GetPreSignedURL(new GetPreSignedUrlRequest
{
BucketName = BUCKET_NAME,
Key = TEST_FILE,
Expires = DateTime.Now.AddHours(1)
});
OpenURL(url);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
示例6: PostUpload
public async System.Threading.Tasks.Task<IHttpActionResult> PostUpload(string folder, string filekey)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data/Temp/FileUploads");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
var provider = new MultipartFormDataStreamProvider(root);
try
{
var result = await Request.Content.ReadAsMultipartAsync(provider);
}
catch (Exception ex)
{
}
try
{
string bucketName = "aws-yeon-test-fims-support";
var credentials = new StoredProfileAWSCredentials("s3");
IAmazonS3 client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.APNortheast2);
foreach (var file in provider.FileData)
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2),
FilePath = file.LocalFileName
//ContentType = "text/plain"
};
putRequest.Headers.ContentLength = 168059;
PutObjectResponse response = client.PutObject(putRequest);
}
}
catch (AmazonS3Exception amazonS3Exception)
{
return InternalServerError(amazonS3Exception);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
finally
{
}
return Ok();
}
示例7: CreateTestBase
public static void CreateTestBase()
{
Client = new AmazonS3Client();
bucketName = S3TestUtils.CreateBucket(Client);
Client.PutObject(new PutObjectRequest
{
BucketName = bucketName
});
}
示例8: Convert
public Uri Convert(byte[] bytes)
{
string url;
using (IAmazonS3 client = new AmazonS3Client(AccessKey, SecretKey, RegionEndpoint.USEast1))
{
Guid imageFilename = Guid.NewGuid();
PutObjectRequest request = BuildRequest(imageFilename, new MemoryStream(bytes));
client.PutObject(request);
url = string.Format("https://s3.amazonaws.com/{0}/{1}/{2}", BucketName, FolderName, imageFilename);
}
return new Uri(url);
}
示例9: Save
public Uri Save(string base64ImageString)
{
string url;
using (IAmazonS3 client = new AmazonS3Client(AccessKey, SecretKey, RegionEndpoint.USEast1))
{
MemoryStream ms = GetMemoryStreamFromBase64(base64ImageString);
Guid imageFilename = Guid.NewGuid();
PutObjectRequest request = BuildRequest(imageFilename, ms);
client.PutObject(request);
url = "https://s3.amazonaws.com/FireTower_DisasterImages/disasters/" + imageFilename.ToString();
}
return new Uri(url);
}
示例10: PutObj
private static string PutObj(AmazonS3Client client)
{
string time = DateTime.Now.ToString("hhmmsstt");
// Create a PutObject request
PutObjectRequest putObjRequest = new PutObjectRequest
{
BucketName = "com.loofah.photos",
Key = time,
FilePath = "C:\\Users\\Ryan\\Pictures\\cz1jb.jpg"
};
// Put object
PutObjectResponse putObjResponse = client.PutObject(putObjRequest);
return time;
}
示例11: CreateVersion
public void CreateVersion(Version version)
{
if (version == null)
throw new ArgumentNullException("version", "Version cannot be null.");
if (version.AppKey == Guid.Empty)
throw new ArgumentException("App key cannot be empty.", "version.AppKey");
try
{
using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
{
var appsController = new Apps(Context);
var app = appsController.GetApp(version.AppKey);
version.GroupKey = app.GroupKey;
var indexesController = new Internal.Indexes(Context);
using (var stream = version.Serialise())
{
string indexPath = GetAppVersionsIndexPath(version.AppKey);
var index = indexesController.LoadIndex(indexPath);
if (index.Entries.Any(e => e.Key == version.Key))
{
throw new DeploymentException("Index already contains entry for given key!");
}
using (var putResponse = client.PutObject(new PutObjectRequest()
{
BucketName = Context.BucketName,
Key = string.Format("{0}/{1}/{2}", STR_VERSIONS_CONTAINER_PATH, version.Key.ToString("N"), STR_INFO_FILE_NAME),
InputStream = stream,
})) { }
index.Entries.Add(new Internal.EntityIndexEntry() { Key = version.Key, Name = CreateVersionIndexName(version) });
Internal.Indexes.NameSortIndex(index, true);
indexesController.UpdateIndex(indexPath, index);
}
}
}
catch (AmazonS3Exception awsEx)
{
throw new DeploymentException("Failed creating version.", awsEx);
}
catch (Exception ex)
{
throw new DeploymentException("Failed creating version.", ex);
}
}
示例12: CreateS3Bucket
public void CreateS3Bucket(string bucketName, string key, Credentials credentials, AmazonS3Config config)
{
var s3Client = new AmazonS3Client(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.SessionToken, config);
string content = "Hello World2!";
// Put an object in the user's "folder".
s3Client.PutObject(new PutObjectRequest
{
BucketName = bucketName,
Key = key,
ContentBody = content
});
Console.WriteLine("Updated key={0} with content={1}", key, content);
}
示例13: CreateInstance
public void CreateInstance(Instance instance)
{
if (instance == null)
throw new ArgumentNullException("instance", "Instance cannot be null.");
if (instance.TargetKey == Guid.Empty)
throw new ArgumentException("Target key cannot be empty.", "instance.TargetKey");
using (var stream = instance.Serialise())
{
try
{
using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
{
var targetsController = new Targets(Context);
if (!targetsController.TargetExists(instance.TargetKey))
throw new TargetNotFoundException(String.Format("Target with the key \"{0}\" could not be found.", instance.TargetKey));
var indexesController = new Internal.Indexes(Context);
string indexPath = GetTargetInstancesIndexPath(instance.TargetKey);
var instanceIndex = indexesController.LoadIndex(indexPath);
if (instanceIndex.Entries.Any(e => e.Key == instance.Key))
{
throw new DeploymentException("Target instances index already contains entry for new instance key!");
}
using (var putResponse = client.PutObject(new PutObjectRequest()
{
BucketName = Context.BucketName,
Key = string.Format("{0}/{1}/{2}", STR_INSTANCES_CONTAINER_PATH, instance.Key.ToString("N"), STR_INFO_FILE_NAME),
InputStream = stream,
})) { }
instanceIndex.Entries.Add(new Internal.EntityIndexEntry() { Key = instance.Key, Name = instance.Name });
Internal.Indexes.NameSortIndex(instanceIndex);
indexesController.UpdateIndex(indexPath, instanceIndex);
}
}
catch (AmazonS3Exception awsEx)
{
throw new DeploymentException("Failed creating instance.", awsEx);
}
}
}
示例14: CreateTarget
public void CreateTarget(Target target)
{
if (target == null)
throw new ArgumentNullException("target", "Target cannot be null.");
if (target.GroupKey == Guid.Empty)
throw new ArgumentException("Group key cannot be empty.", "target.GroupKey");
using (var stream = target.Serialise())
{
try
{
using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
{
var groupsController = new Groups(Context);
if (!groupsController.GroupExists(target.GroupKey))
throw new GroupNotFoundException(String.Format("Group with the key \"{0}\" could not be found.", target.GroupKey));
var indexesController = new Internal.Indexes(Context);
string indexPath = GetGroupTargetsIndexPath(target.GroupKey);
var appIndex = indexesController.LoadIndex(indexPath);
if (appIndex.Entries.Any(e => e.Key == target.Key))
{
throw new DeploymentException("Index already contains entry for given key!");
}
using (var putResponse = client.PutObject(new PutObjectRequest()
{
BucketName = Context.BucketName,
Key = string.Format("{0}/{1}/{2}", STR_TARGETS_CONTAINER_PATH, target.Key.ToString("N"), STR_INFO_FILE_NAME),
InputStream = stream,
})) { }
appIndex.Entries.Add(new Internal.EntityIndexEntry() { Key = target.Key, Name = target.Name });
Internal.Indexes.NameSortIndex(appIndex);
indexesController.UpdateIndex(indexPath, appIndex);
}
}
catch (AmazonS3Exception awsEx)
{
throw new DeploymentException("Failed creating target.", awsEx);
}
}
}
示例15: UploadContentFile
public string UploadContentFile(string uniqueName, string fileExtension, Stream fileStream, bool makePrivate = false)
{
// file extension has dot at start.
string fileName = string.Format("{0}.{1}", uniqueName, fileExtension);
IAmazonS3 client = null;
using (client = new AmazonS3Client(_awsAccessKeyId, _awsSecretAccessKey))
{
fileStream.Position = 0;
try
{
// simple object put
PutObjectRequest request = new PutObjectRequest()
{
//ContentBody = "You are such a brilliant person reading open documents.",
BucketName = _awsBucketName,
Key = string.Format("{0}/{1}", _awsContentFilePath, fileName),
CannedACL = S3CannedACL.PublicRead,
InputStream = fileStream
};
PutObjectResponse response = client.PutObject(request);
string url = string.Format("https://{0}.s3-{1}.amazonaws.com/{2}/{3}",
_awsBucketName, _awsRegion, _awsContentFilePath, fileName
);
return url;
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Please check the provided AWS Credentials.");
throw new Exception("Storage access denied.");
}
else
{
Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
throw new Exception("Write failed.");
}
}
}
}