简体   繁体   中英

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

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();

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM