繁体   English   中英

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

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

我正在使用 Node.js 将二进制数据发送到 PHP。 POST 数据包含一个 JSON 字符串,后跟换行符,然后是二进制部分。

从节点发送数据:

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
);

...并在 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);
}

这有效,但我收到警告:

PHP 警告:未知:输入变量超过 1000。

有什么方法可以防止 PHP 尝试解析 POST 数据?

我刚刚发现了 PUT。 它完全符合我的要求。 只需将 axios.post(url, buf) 更改为 axios.put(url, buf)。 在 PHP 方面,没有尝试解码任何内容 - 由脚本来解释数据。

从 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);
  });

和 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