n00n
n00n

Reputation: 664

HTTPful attach file and json-body in one request

I need to upload files via Rest and also send some configuration with it.

Here is my example code:

$this->login();
$files = array('file'=>'aTest1.jpg');
$data =
    array(
        'name'=>'first file',
        'description'=>'first file description',
        'author'=>'test user'
    );
$response = Request::post($this->getRoute('test'))
    ->addHeader('Authorization', "Bearer " . $this->getToken())
    ->attach($files)
    ->body(json_encode($data))
    ->sendsJson()
    ->send();

I am able to send the file or able to send the body. But it is not working if I try with both...

Any Hint for me?

Regards n00n

Upvotes: 5

Views: 2999

Answers (2)

bloub
bloub

Reputation: 101

the body() method erases payload content, so after calling attach(), you must fill payload yourself :

$request = Request::post($this->getRoute('test'))
  ->addHeader('Authorization', "Bearer " . $this->getToken())
  ->attach($files);
foreach ($parameters as $key => $value) {
  $request->payload[$key] = $value;
}
$response = $request
  ->sendsJson();
  ->send();

Upvotes: 3

jjwdesign
jjwdesign

Reputation: 3322

For those coming to this page via Google. Here's an approach that worked for me.

Don't use attach() and body() together. I found that one will clear out the other. Instead, just use the body() method. Use file_get_contents() to get binary data for your file, then base64_encode() that data and place it into the $data as a parameter.

It should work with JSON. The approach worked for me with application/x-www-form-urlencoded mime type, using $req->body(http_build_query($data));.

$this->login();
$filepath = 'aTest1.jpg';
$data =
    array(
        'name'=>'first file',
        'description'=>'first file description',
        'author'=>'test user'
    );
$req = Request::post($this->getRoute('test'))
    ->addHeader('Authorization', "Bearer " . $this->getToken());

if (!empty($filepath) && file_exists($filepath)) {
    $filedata = file_get_contents($filepath);
    $data['file'] = base64_encode($filedata);
}

$response = $req
    ->body(json_encode($data))
    ->sendsJson();
    ->send();

Upvotes: 3

Related Questions