简体   繁体   English

如何有效地将二进制数据从 node.js 发布到 PHP

[英]How to efficiently POST binary data from node.js to PHP

I'm using Node.js to send binary data to PHP.我正在使用 Node.js 将二进制数据发送到 PHP。 The POST data contains a JSON string, followed by newline, then the binary part. POST 数据包含一个 JSON 字符串,后跟换行符,然后是二进制部分。

Sending data from Node:从节点发送数据:

let binary = null;
if('binary' in msg)
{
    binary = msg.binary;
    delete msg.binary;
}
let buf = Buffer.from(JSON.stringify(msg) + (binary === null ? '' : '\n'));
if(binary !== null) buf = Buffer.concat([buf, binary]);
let response = await axios.post
(
    url,
    buf
);

...and receiving it in PHP: ...并在 PHP 中接收它:

$binary = null;
$in = file_get_contents('php://input');
$pos = strpos($in, "\n");
if($pos === false)
{
    $_POST = json_decode($in, true);
}
else
{
    $_POST = json_decode(substr($in, 0, $pos), true);
    $binary = substr($in, $pos + 1);
}

This works, but I'm getting a warning:这有效,但我收到警告:

PHP Warning: Unknown: Input variables exceeded 1000. PHP 警告:未知:输入变量超过 1000。

Is there any way to prevent PHP from trying to parse the POST data?有什么方法可以防止 PHP 尝试解析 POST 数据?

I just discovered PUT.我刚刚发现了 PUT。 It does exactly what I'm looking for.它完全符合我的要求。 Just have to change axios.post(url, buf) to axios.put(url, buf).只需将 axios.post(url, buf) 更改为 axios.put(url, buf)。 On the PHP side, there's no attempt to decode anything - it is up to the script to interpret the data.在 PHP 方面,没有尝试解码任何内容 - 由脚本来解释数据。

Separate file from json:从 json 分离文件:

let formData = new FormData();
formData.append('file', fs.createReadStream(filepath));
formData.append('json', '{"jsonstring":"values"}');
axios.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }).then((response) => {
    fnSuccess(response);
  }).catch((error) => {
    fnFail(error);
  });

And PHP和 PHP

$jsonstring  = $_POST['json'];
$json = json_decode($jsonstring,true); // array

$uploaddir = "path/to/uploads/";
$uploadfile = $uploaddir . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
{
  $uploadfile // is the path to file uploaded
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM