【发布时间】:2019-06-09 09:02:29
【问题描述】:
我正在尝试在基于 Laravel 的端点中使用 cURL 获取发布的数据。在我接收数据的 API 控制器中,我能够接收除媒体文件之外的所有数据。我使用$request->hasFile('file') 检查文件是否存在,但它返回false。我也尝试使用$request->file('file') 获取文件,但它返回 null。
当我使用$request->get('file') 时,我得到以下响应。
file":{"name":"/Users/name/File/path/public/media/aaaah.wav","mime":null,"postname":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}
【问题讨论】:
标签: php laravel curl laravel-request