10
7

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 3 years have passed since last update.

でかいデータのAjaxリクエストを圧縮して軽くしてPHPで受け取る

Last updated at Posted at 2020-11-17

数MBくらいあるデータをリクエストボディに載せたいけど、少しは軽くしたいのでゴニョゴニョ。

JS側

import pako from 'pako'
import axios from 'axios'

const bigObject = { /* 超でかいObject */ }
const json = JSON.stringify(bigObject)
const gzipped = pako.gzip(json, { to: 'string' })
const base64Encoded = btoa(gzipped)
axios.post('/api/foo', { compressed: base64Encoded })
  • JSONにする
  • pako を使ってgzip圧縮する
  • btoa() を使ってBase64エンコードする
  • 文字列としてリクエストする

PHP側

$gzipBinary = base64_decode($_POST['compressed']);
$json = gzdecode($gzipBinary);
$data = json_decode($json, true);

余計な処理は入るけど、リクエストボディが 1.5MB から 250KB くらいまでは小さくなったので満足。

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?