2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

S3にアップロードした画像をAjaxで取得する

Posted at

やりたいこと

デバッグ等で、S3にアップロードされているかどうかをチェックした後に、
URLを差し替えて画像を表示したいというニッチなニーズに遭遇。

普通に何も考えずに実装すると

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

という感じに怒られる。
ちゃんとヘッダを設定して、クロスドメインを有効にしましょうという話。

S3のCORS設定

s3_cors_settings.png

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

AjaxでcrossDomainを有効にする

    _.each($('.s3-image-debugger'), function(img, _idx) {
      var $img = $(img);
      var src = $img.attr('src');

      if (src && src.match(/s3-ap-northeast-1.amazonaws.com/)) {
        $.get(src, {crossDomain: true}).fail(function() {
          $img.attr('src', src.replace('production', 'test'));
        });
      }
    });

かなり急いで作ったので雑ですが、意図した挙動になりました :innocent:

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?