我正在尝试使用cURL在基于Laravel构建的端点中发布数据。在我接收数据的API控制器中,我可以接收除媒体文件以外的所有数据。我使用$request->hasFile('file')
检查文件是否存在,但返回false。我还尝试使用$request->file('file')
获取文件,但它返回null。
当我使用$request->get('file')
时,得到以下响应。
文件”:{“名称”:“ /用户/名称/文件/路径/public/media/aaaah.wav”,“哑剧”:null,“邮编”:null}
下面,我使用$headers[] = "Content-Type: application/json";
将收件人从数组转换为字符串。有人可以帮助我理解为什么当我使用$request->hasFile('file')
和$request->file('file')
时在Laravel方法中没有收到cURL发布的文件吗?
AppController
public function postCurlData()
{
$endPoint = 'http://127.0.0.1:9000/api';
$apiKey = '****';
$url = $endPoint . '?key=' . $apiKey;
$dir = '/Users/name/File/path/app/public/media/test.wav'; // full directory of the file
$curlFile = curl_file_create($dir);
$data = [
'recipient' => ['44909090', '44909090'],
'content' => 'i love to code',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
我正在接收数据的端点:
APIController
public function receiveCurlData()
{
$apiKey = $request->get('key');
if (($apiKey)) {
return response()->json([
'status' => 'success',
'content' => $request->get('content'),
'recipient' => $request->get('recipient'),
'file' => $request->hasFile('file')
]);
}
}
回复
{"status":"success","content":"I love to code","recipient":
["44909090","44909090"],"file":false}
答案 0 :(得分:0)
此答案与您的问题有关: how to upload file using curl with php。
您应该删除
$headers = array();
$headers[] = "Content-Type: application/json";
和
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
并删除json_encode()并将其替换为普通数组
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);