[英]HTTPful attach file and json-body in one request
我需要通過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
對於那些通過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();
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.