0

ajaxでリクエストを送り、
バックエンドで「Intervention Image」を利用して画像を加工したものを
ローカルにダウンロードしたいのですが、
加工した画像データをblobに変換することができず詰まっておりました。

Intervention Imageにstreamで返却する関数などもあるとのことで
やってみてたのですが、
フロントに戻ってきた時点で文字化けしてしまいという状況でした。

どなたかお助けしていただけないでしょうか。
よろしくお願いします。

javascript

$.ajax({
        type: 'GET',
        url: '/export/img',
        data: {
            'img_type': imgType
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    }).done((response) => {
        const blob = new Blob([response], {type: 'image/png'});
        const filename = 'test.png'
        const downloadUrl  = (window.URL || window.webkitURL).createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = filename;
        link.click();
        (window.URL || window.webkitURL).revokeObjectURL(downloadUrl);
    }).fail(() => {
        $("#errorModal").modal("show");
    });

backend(controller)

public function export(Request $request)
    {
        // 画像生成処理
        $img = $this->service->createImg($request->img_type);
        return $img->stream('png')->__toString();
    }
}

1 件の回答 1

1

自己解決できました!!

javascript

function exportImg(imgType) {
  $.ajax({
      type: 'GET',
      url: '/export/img',
      data: {
        'img_type': imgType
      },
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  }).done((response) => {
      const base64 = response.encoded;
      a = document.createElement("a");
      a.href = base64;
      a.download = dayjs().format("YYYYMMDDHHmmss") +".png";
      a.click();
      $("#spinner").css("display", "none");
  }).fail(() => {
      $("#errorModal").modal("show");
  });
}

php

public function export(Request $request)
{
    // 画像生成処理
    $img = $this->service->createImg($request->img_type);
    return $img->encode('png')->encode('data-url');
}

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。