how to pass a file data in an object array to be accepted by a REST endpoint made of php?

Viewed 103

so in postman, we have a form-data upload button if we want to attach a file and use POST to call an API endpoint. now my question is,

how to add a file if we are gonna use the body as a raw text payload request if let's say the body is like this ?

{
    "id": 1,
    "mydata": [
      {
         "entity_id": 1,
         "upload_file": // WHAT TO PUT HERE ?
      },
      {
         "entity_id": 2,
         "upload_file": //WHAT TO PUT HERE ?
      }
    ]
}

In backend, we're suppose to catch an attached or uploaded file using $_FILES global variable.. but if the payload request is an object array... how are we suppose to include an attached file or upload file in the payload ? .. please see example above

1 Answers

If you want to pass it in raw data you can encode to base64 for example and then to put it inline.

$imagedata = file_get_contents("/path/to/file");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Take the output of $base64 and put it as a raw data.

In addition, by iterating on $_FILES you will get all uploaded files with their keys. in backend you can link key in $_FILES to your object in array.

Related