バケットにテキストをアップロードする

次は、単純なアップロードのサンプル。文字列データをアップロードする。ファイルをアップロードしたようなカンジ。前回のサンプルを実行することでほとんど準備は整っているのだが、一点だけ追加しないといけない設定があるので先にその説明を。

前回はバケットのクロスドメイン設定を「GET」だけ許可したのだが、今回のサンプルを実行するには「PUT」も許可しないといけない。ま、今後必要になりそうな「POST」も「DELETE」も同時に許可しておきましょうか。

S3管理画面→バケット選択→Properties→Permissions→Edit CORS Configuration
で、以下を設定する。

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

その後、以下のhtmlを保存して、ブラウザにD&D後、テキストボックスに何か入力して送信ボタンを押すと、バケットにtest.txtというファイルが作成されているハズ。

<!DOCTYPE html>
<html>
<head>
<title>AWS サンプル</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
<h1>AWS サンプル</h1>

<input type="text" id="txt"/>
<button id="btn1">送信</button>
<div id="status">結果</div>

<script src="http://sdk.amazonaws.com/js/aws-sdk-2.0.0-rc13.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">//<![CDATA[
$(function()
{
  AWS.config.region = 'ap-northeast-1';
  AWS.config.update({
    accessKeyId: 'アクセスキー',
    secretAccessKey: 'シークレットキー'
  });

  var s3 = new AWS.S3({params: {Bucket: 'バケット名'}});

  $("#btn1").click( function()
  {
    var txt = $("#txt").val();
    if( !txt ) return;

    var params = {
      Bucket: 'バケット名',
      Key: "test.txt",
      Body: txt
    };
    s3.putObject(params, function(err, data)
    {
      if(err)
      {
        console.dir(err);
        $("#status").html("エラー");
      }

      $("#status").html("成功");
    });
  });
});
//]]></script>
</body>
</html>