1
0

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.

Ajaxでテキストをgzipして他のパラメータと一緒にPOSTするテスト

1
Posted at

クライアント側でgzipをした後、バイナリで送信してみた。
gzipはこちらを使用してみる
https://www.npmjs.com/package/zlibjs

バイナリはファイルとして送信するといいらしい。

クライアント(javascript)
let a = "クライアント側でgzipをした後、バイナリで送信してみた。";
console.log("元データ:"+encodeURIComponent(a).replace(/%../g,"x").length+"Bytes");

var gzip = new Zlib.Gzip(unicode2utf8_uint8array(a));
var compressed = gzip.compress();
console.log("圧縮:"+compressed.length+"Bytes");

let fd = new FormData();
fd.append('hoge', "aaa");
fd.append('hoge2', "bbb");
fd.append('hoge3', new Blob([compressed], {type: "application/octet-binary"}));

 $.ajax({url: "https://xxxx.com/hoge.php",
  type: "POST",
  contentType:false,
  processData: false,
  cache: false,
  data: fd,
  }).then(function(data, textStatus, jqXHR) {
     alert(data);
  },function(jqXHR, textStatus, errorThrown) {});
}

unicode2utf8_uint8arrayは、https://qiita.com/ukyo/items/1626defd020b2157e6bfから。
ありがとうございます!

送信後は、サーバーにファイルとして保存されている。

サーバー側(PHP)

header('Content-Type: text/html; charset=UTF-8');
header("Access-Control-Allow-Origin: *");

echo "hoge:".$_POST["hoge"];
echo "hoge2:".$_POST["hoge2"];

var_dump($_FILES["hoge3"]);

echo "[". gzdecode(file_get_contents($_FILES["hoge3"]["tmp_name"])) ."]";

テスト結果

元データ82Bytes
圧縮98Bytes
hoge:aaa
hoge2:bbb
array(5) {
  ["name"]=>
  string(4) "blob"
  ["type"]=>
  string(24) "application/octet-binary"
  ["tmp_name"]=>
  string(14) "/tmp/phpHlyZxg"
  ["error"]=>
  int(0)
  ["size"]=>
  int(98)
}
[
クライアント側でgzipをした後バイナリで送信してみた

]

普通のパラメータとバイナリが一緒に送られていますね。
gzip後のサイズと送信後に受け取ったサイトが同じなので、そのまま送られているはず。たぶん。

よく見ると圧縮後のサイズが増えとるよ…

送信前にバイト数を確認して、そのまま送るか圧縮するか判断するべきですね。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?