【问题标题】:Posting through CURL and Receiving in Laravel 5.5在 Laravel 5.5 中通过 CURL 发布和接收
【发布时间】:2019-01-15 14:48:57
【问题描述】:

我正在尝试在基于 Laravel 的端点中使用 cURL 获取发布的数据。在我接收数据的 API 控制器中,我能够接收除媒体文件之外的所有数据。我使用$request->hasFile('file') 检查文件是否存在,但它返回错误。我也尝试使用 $request->file('file') 获取文件,但它返回 null。

当我使用$request->get('file') 时,我得到以下响应。

Laravel:5.5

PHP 7.2.1

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

我接收数据的端点:

API控制器

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}

【问题讨论】:

  • 使用 Guzzle 会更轻松:docs.guzzlephp.org/en/stable
  • @ceejayoz,为什么你更喜欢 Guzzle 而不是 Curl?
  • 因为它是专门为这类事情设计的,并且会自动处理大多数常见的 cURL 调用错误。
  • “谁能帮我理解为什么我的 Laravel 方法没有收到 cURL 发布的文件” - 发生这种情况因为你搞砸了内容类型。 PHP 没有从 JSON 中提取文件上传数据的默认机制;您需要发送multipart/form-data 请求。
  • @misorude,即使是multipart/form-data,我仍然无法获取文件。这实际上是我第一次尝试:)

标签: php laravel


【解决方案1】:

如果您要发送文件,那么我建议您设置 curl 安全上传:

curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);

然后您可能需要更改标头的 Content-Type 并进行设置:

"Content-Type: multipart/form-data"

另外我通常使用这种方法而不是curl_file_create

if ( class_exists('CurlFile') ) {
  $file = new CurlFile('path-to-the-file', 'application/octet-stream');
} else {
  $file = '@' . realpath('path-to-the-file');
}

无论如何我会说(但不完全确定)您的代码的问题在于设置为 JSON 的 Content-Type 标头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多