I have a bucket with images and that bucket content are being distributed from a Cloudfront distribution through a OAI associated between Cloudfront distribution and S3 Bucket. My problem is when i try to display any image from that bucket, the browser try to download instead display. I read some questions here on SO about the same problem, and i saw that the metadata from the image should be image/jpeg or image/png, so i did this, but for some reason some images are try to download instead display even after that i changed the metadata content-type according the image extension. What should be doing to fix that problem?
CodePudding user response:
You can try the following to solve your problem:
- You check if your image is jpg/png/img format.
- When you have uploaded your image in your Amazon Simple Storage Service (Amazon S3) you can select your image > properties(on the top right). You will see the link to the image and it will look something like this. Now if you try to open that file using the link you will see the access denied message. S3 files are private by default, as many people use it to store sensitive data. You'll need to change the permissions of the files so they can be accessed by the outside world. Click Properties on the top right. Then open the Permissions section and add an item. We're going to grant "Everyone" the right to read the image.Click on edit ACL . Check all the read boxes for Everyone (public access) . Check the "I understand the effects..." box. Now click on the Save changes button. Now copy the object URL and open in a new tab. The image will now display and not download.
This is the link I created with cloud front
Now lets see how I created it: 1.Create cloudfront distribution. You can see the necessary steps here and the important note here 2.Be 100% sure that the bucket image is public and not private(u will get XML error if it private) 3. Keep everything as default values. 4.After creating cloudfront distribution wait for 15-30 min for it to be enabled! 5. Upload an image to S3 for testing. Make all the values default (recommended values). 6.Now open CloudFront domain with the image and tada! your image is now ready. Please follow me as I spent 5-6 hours solving your question!
CodePudding user response:
I solved the problem that way:
- python script to set the Metadata Content Type of images according its extension. Basically, the core of script is the function below:
def update_metadata(key, bucket, extension):
s3.copy_object(Key=key, Bucket=bucket,
CopySource={"Bucket": bucket, "Key": key},
ContentType=f"image/{extension}",
MetadataDirective="REPLACE")
parameters:
- image name
- bucket name
- image extension
That way, the script will overwrite the current Content Type and image will be displayed when request through browser. The library used was boto3.
Important point: After run the changes, it will be necessary create an invalidation on Cloudfront distribution for everything works well.