2017年3月27日月曜日

htmlのimg tag内base64画像をサーバーに送信(cakephpの場合)

<img src="data:image/jpeg;base64,/9j.....=">

このsrcの画像をサーバーに送りたい。

JS側は以下のような感じ
function asyncSend() {
      // Generate the image data
      var base64image  = $("#createdPic").attr('src');
      // Sending the image data to Server
      $.ajax({
          method: "POST",
          url: '/Projects/ajaxCall',
          data: { "base64image" : base64image },
          success: function (msg) {
              console.log("OK");
          },
          error: function (response, desc, exception) {
              console.log("NG");
          }
      });
    }

サーバー側はcakephpを使用
public function ajaxCall() {
$this->autoRender = FALSE; //Viewある場合不要
    if($this->request->is('ajax')) {
            $img = $this->request->data['base64image'];
            $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img); //base64_decode() でバイナリに戻す
    $file = 'image.jpeg';
    $success = file_put_contents($file, $data);
        }
}

参考:http://stackoverflow.com/questions/1532993/i-have-a-base64-encoded-png-how-do-i-write-the-image-to-a-file-in-php

0 件のコメント:

コメントを投稿