1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Check my question well.. I said Json and audio. There are two different formats here i am sending to my api. I know you can't send audio file as json that is why i haven't json_encoded it in my code.
But you are saying in the header Content-Type: application/json : it is JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.