我正在使用 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 資料?
uj5u.com熱心網友回復:
從 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
}
uj5u.com熱心網友回復:
我剛剛發現了 PUT。它完全符合我的要求。只需將 axios.post(url, buf) 更改為 axios.put(url, buf)。在 PHP 方面,沒有嘗試解碼任何內容 - 由腳本來解釋資料。
雖然這允許我做我想做的事,但以這種方式使用它違反了HTTP 規范。就我而言,這沒什么大不了的,因為它是在內部使用的,它可以防止 PHP 的一些不必要的(對于這種情況)預處理和檔案 I/O。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/426780.html
