我需要从S3检索图像。我不能公开文件夹,我不能使用预先签名的URL,所以我剩下的就是GetObject();.现在我必须将我要回来的图像设置为Iframe的源。为此,我使用的是HttpWebHandler。问题是,如果我检索一个HTML页面,它工作正常。但是当我试图恢复图像时,我得到的只是垃圾数据。这是我的代码:
public void ProcessRequest(HttpContext context)
{
NameValueCollection appConfig = ConfigurationManager.AppSettings;
_accessKeyId = appConfig["AWSAccessKey"];
_secretAccessKeyId = appConfig["AWSSecretKey"];
S3 = new AmazonS3Client(_accessKeyId, _secretAccessKeyId);
string responseBody = "";
var request = new GetObjectRequest()
.WithBucketName(bucketName).WithKey("020/images/intro.jpg");
var responseHeaders = new ResponseHeaderOverrides
{
ContentType = "image/jpeg"
};
request.ResponseHeaderOverrides = responseHeaders;
using (var response = S3.GetObject(request))
{
using (var responseStream = response.ResponseStream)
{
using (var reader =
new StreamReader(responseStream))
{
responseBody = reader.ReadToEnd();
}
}
}
context.Response.Write(responseBody);
context.Response.Flush();
context.Response.End();
}
}
答案 0 :(得分:2)
这里有几个问题:
请改为尝试:
using (var response = S3.GetObject(request))
{
using (var responseStream = response.ResponseStream)
{
context.Response.ContentType = "image/jpeg";
var buffer = new byte[8000];
int bytesRead = -1;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
}
context.Response.End();