从S3获取图像

时间:2012-05-22 03:28:25

标签: c# amazon-s3

我需要从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();
        }
}

1 个答案:

答案 0 :(得分:2)

这里有几个问题:

  1. 您正在设置亚马逊回复的内容类型,而不是来自您的应用程序的回复
  2. 您正在使用StreamReader将流的内容作为文本读取,然后将其作为文本写回来
  3. 请改为尝试:

    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();