Getting Images from S3

amazon-s3, c#

Solution

There are a couple of problems here:

- You are setting the Content-Type on the response coming back from amazon, but not on the response from your application

- You are using a StreamReader to read the content of the stream as text and then writing it back as text

Try this instead:

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

Problem

I need to retrieve images from S3. I can't make the folder public and I cant use presigned URL's so all I am left with is GetObject();. Now the image that I'll get back has to be set as a source for an Iframe. To do that I am using a HttpWebHandler. The issue is that if i retrieve a html page it is working fine. But when I try to get an image back, all i get is junk data. Here is my code: ``` 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(); } } ```

Original source

Related problems