我從Request.Files [0]獲得了我的圖像。現在,我該如何將這張圖片上傳到S3?我在AWS .NET API中看到,在放置一個字符串對象時,您必須指定ContentBody。我將如何獲取我的文件的內容正文?ASP.NET MVC - 將圖像上傳到Amazon S3
回答
var file = Request.Files[0];
PutObjectRequest request = new PutObjectRequest();
request.BucketName = "mybucket"
request.ContentType = contentType;
request.Key = key;
request.InputStream = file.InputStream;
s3Client.PutObject(request);
很可能這是一個Base64編碼的字符串,但您應該檢查S3文檔以確保它。如果是,則應使用Convert.ToBase64String()並將字節數組傳遞給它。
下面是一些您可以嘗試的示例代碼。我沒有測試它,但它應該可以幫助您正確的觀念:
if (Request.Files.Count >= 1) {
var file = Request.Files[0];
var fileContents = new byte[file.ContentLength];
file.InputStream.Read(fileContents, 0, file.ContentLength);
var fileBase64String = Convert.ToBase64String(fileContents);
// now you can send fileBase64String to the S3 uploader
}
這並不工作,但沒有什麼工作是使用file.InputStream作爲的InputStream的屬性PutObjectRequest對象。謝謝你的幫助! – 2010-09-23 19:50:25
與如何使用文件夾和授予所有用戶進行只讀訪問稍微更多的細節。 HTML:
C#
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0) // accept the file
{
string accessKey = "XXXXXXXXXXX";
string secretKey = "122334XXXXXXXXXX";
AmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
MemoryStream ms = new MemoryStream();
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName("mybucket")
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey("testfolder/test.jpg").InputStream = file.InputStream;
S3Response response = client.PutObject(request);
}
更多詳細信息,請訪問:http://bradoyler.com/post/3614362044/uploading-an-image-with-aws-sdk-for-net-c
博客文章是無效鏈接。 – swbradshaw 2017-11-29 20:07:36
PurObjectRequest request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,
Key = string.Format("folderyouwanttoplacethefile/{0}", file.FileName),
InputStream = file.InputStream
};
YourS3client.PutObject(request);
請添加一些關於它如何工作的解釋。 – 2016-10-03 20:18:17
感謝代碼位,也爲我解決了一些問題。 – Chaddeus 2010-11-08 04:27:48