5

我需要通过 Rest 上传文件并发送一些配置。

这是我的示例代码:

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

我能够发送文件或能够发送正文。但是,如果我尝试两者都行不通...

对我有任何提示吗?

问候 n00n

4

2 回答 2

3

对于那些通过谷歌来到这个页面的人。这是一种对我有用的方法。

不要一起使用 attach() 和 body()。我发现一个会清除另一个。相反,只需使用 body() 方法。使用 file_get_contents() 获取文件的二进制数据,然后使用 base64_encode() 该数据并将其作为参数放入 $data 中。

它应该适用于 JSON。该方法适用于 application/x-www-form-urlencoded mime 类型,使用 $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();
于 2016-08-11T20:19:58.853 回答
3

body()方法会擦除payload内容,因此在调用之后attach(),您必须payload自己填写:

$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();
于 2016-10-31T17:13:44.470 回答