简体   繁体   English

将带有 php (curl) 的 Json 和音频文件发布到 Laravel API

[英]Post Json and audio file with php (curl) to a laravel API

I am posting json and audio file to my api built on laravel with the code below我正在使用下面的代码将 json 和音频文件发布到我在 laravel 上构建的 api

     $endPoint = 'http://localhost:9000/api/audio/send';
     $apiKey = 'anvx7P7ackndaD8MvXlufSaG4uJ901raoWIwMPGZ93dkH';
     $url = $endPoint . '?key=' . $apiKey;
     $curlFile = new \CURLFile('/Users/desktop/myapp/public/Voice/aaaah.wav');            
     $data = array("request" => 
     json_encode(array("test" => "First audio ",'recipient' =>['442342342', '35345242'])) . ";
     type=application/json","file" => "@d8696c304d09eb1.wav;type=audio/wav");

                $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, $data);
                $result = curl_exec($ch);
                $result = json_decode($result, TRUE);
                curl_close($ch);
            return $result;

When i submit my json to the api, it returns null from the api.当我将我的 json 提交给 api 时,它从 api 返回 null。 Meaning no data is being posted to my api.这意味着没有数据被发布到我的 api。 Is there any error with how i am posting my json and audio file to the laravel api please?请问我如何将我的json和音频文件发布到laravel api有什么错误吗?

PS: Beginner in PHP PS:PHP初学者

You cannot post files in a JSON!.您不能以 JSON 格式发布文件!。

A normal POST request is needed (the one that gets generated from the <form> element) for posting a file.需要一个普通的 POST 请求(从<form>元素生成的请求)来发布文件。

If you are bound to send the file using JSON, base64_encode it and send.如果您必须使用 JSON 发送文件,请对其进行 base64_encode 并发送。 On the other end though, the server will need to base64_decode it first.但在另一端,服务器需要先对它进行 base64_decode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM