Google cloud storage image public link to img src

timecatcher picture timecatcher · Oct 2, 2016 · Viewed 8.8k times · Source

Hi I have looked into related questions, but have been unsuccessful in finding an answer. I would like to serve public links from google cloud storage on my website, but they are only available as download links. I am unable to place them as img src to load them. I cannot download the image async from my webpage js because of CORS. Is there a workaround? I was wondering whether I could asynchronously define them as download links initially and force onclick to download them then use file reader to get the blob to use as img src.

UPDATE : I figured out that there was a Chromium issue. I used Firefox with CORS_Everywhere and the requests works. Once my website is live, will I have the same issue for the images? OR is it that CORS just doesn't accept localhost? OR is it browser dependent?

Thanks, timecatcher

Answer

Brandon Yarbrough picture Brandon Yarbrough · Oct 3, 2016

I'm not entirely sure what you're trying to do. It sounds like you'd like to display images in an <img> tag where the source is in GCS. You shouldn't need any sort of CORS policy or Javascript trickery for that, so I may misunderstand your question.

To include GCS images on a website, make sure the image is publicly visible, then just include an image tag like this: <img src="https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME" />.

Edit with answer from the comments:

If you upload an object without specifying a Content-Type, GCS defaults to a generic "application/octet-stream." Web browsers generally default to saving application/octet-stream responses. Make sure JPEG images have the Content-Type "image/jpeg" if you want to serve them via the web.

One more caveat:

There is another path using the https://storage.cloud.google.com/ path, but that one is for users authenticating with their own account's Google cookies, and you generally don't wan to rely on that when serving public content. Use https://storage.googleapis.com.