5

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

n00n
  • 654
  • 1
  • 10
  • 30
  • I'm having the exact same problem. Did you ever figure out how to do this? – jjwdesign Aug 10 '16 at 21:12
  • Don't use attach and body. 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. – jjwdesign Aug 11 '16 at 20:11

2 Answers2

3

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();
jjwdesign
  • 3,272
  • 8
  • 41
  • 66
3

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();
bloub
  • 101
  • 1
  • 3