Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPful attach file and json-body in one request

Tags:

httpful

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

like image 359
n00n Avatar asked May 25 '16 14:05

n00n


2 Answers

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();
like image 171
jjwdesign Avatar answered Sep 18 '22 14:09

jjwdesign


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();
like image 36
bloub Avatar answered Sep 21 '22 14:09

bloub