3

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

1 回答 1

3

这里有几个问题:

  1. 您在从亚马逊返回的响应上设置 Content-Type,而不是在您的应用程序的响应上
  2. 您正在使用 StreamReader 将流的内容作为文本读取,然后将其作为文本写回

试试这个:

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();
于 2012-05-22T03:55:14.540 回答