简体   繁体   中英

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

     $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. Meaning no data is being posted to my api. Is there any error with how i am posting my json and audio file to the laravel api please?

PS: Beginner in PHP

You cannot post files in a JSON!.

A normal POST request is needed (the one that gets generated from the <form> element) for posting a file.

If you are bound to send the file using JSON, base64_encode it and send. On the other end though, the server will need to base64_decode it first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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