繁体   English   中英

一个请求中的HTTPful附加文件和json-body

[英]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.

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