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

RoboPHP
  • 410
  • 4
  • 12

1 Answers1

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.

Vaibhav
  • 628
  • 6
  • 10
  • 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. – RoboPHP Mar 04 '19 at 07:02
  • 1
    But you are saying in the header `Content-Type: application/json` : it is JSON – Tuckbros Mar 04 '19 at 07:08
  • https://stackoverflow.com/questions/4238809/example-of-multipart-form-data – Tuckbros Mar 04 '19 at 07:12