【问题标题】:HTTPful attach file and json-body in one request一个请求中的 HTTPful 附加文件和 json-body
【发布时间】:2016-05-25 14:15:57
【问题描述】:

我需要通过 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

【问题讨论】:

  • 我遇到了完全相同的问题。你有没有想过如何做到这一点?
  • 不要使用附加和正文。我发现一个会清除另一个。相反,只需使用 body() 方法。使用 file_get_contents() 获取文件的二进制数据,然后使用 base64_encode() 该数据并将其作为参数放入 $data 中。它应该适用于 JSON。该方法适用于我的 application/x-www-form-urlencoded mime 类型。

标签: httpful


【解决方案1】:

适用于通过 Google 访问此页面的用户。这是一种对我有用的方法。

不要同时使用 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();

【讨论】:

  • 嗯,这会将整个文件加载到 RAM 中 - 对于多个同时请求可能特别危险
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 2016-02-23
    • 2010-11-17
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2020-11-18
    • 2021-04-10
    相关资源
    最近更新 更多