GuzzleHttp使用Multipart流时获取响应正文(大上传文件)

时间:2019-07-09 17:31:13

标签: php file-upload stream guzzle

我尝试使用MultipartStream方法通过GuzzleHttp上传大文件,它在使用表单数据(API令牌)上传文件时效果很好。

问题是当使用MultipartStream无法获取响应主体时,它返回对象样式而不是像json这样的响应页面

代码:

use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;

class FileHostingAPI
{

public $host            = "https://MyWebsite.com/api/v2/";

public $key1            = ''; // Autorize Key1 from Userpanel
public $key2            = ''; // Autorize Key2 from Userpanel

public $access_token    = ''; // access token got from Authorize method
public $account_id      = ''; // account id got from Authorize method

public function fileUpload($filePath = '')
{
    $resource = fopen($filePath, 'r');
    $stream = \GuzzleHttp\Psr7\stream_for($resource);

    $data['access_token'] = $this->access_token;
    $data['account_id']   = $this->account_id;
    $data['folder_id']   = '';

    $client = new \GuzzleHttp\Client();
    $request = new \GuzzleHttp\Psr7\Request(
        'POST',
        $this->host."file/upload",
        [],
        new \GuzzleHttp\Psr7\MultipartStream(
            [
                [
                    'name'     => 'access_token',
                    'contents' => $this->access_token,
                ],[
                    'name'     => 'account_id',
                    'contents' => $this->account_id,
                ],[
                    'name'     => 'folder_id',
                    'contents' => '',
                ],[
                    'name' => 'upload_file',
                    'contents' => $stream,
                ],
            ]
        )
    );

    $response = $client->send($request);

    print_r($response->getBody());
}
}

当前print_r输出: !!

GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #81
    [size:GuzzleHttp\Psr7\Stream:private] =>
    [seekable:GuzzleHttp\Psr7\Stream:private] => 1
    [readable:GuzzleHttp\Psr7\Stream:private] => 1
    [writable:GuzzleHttp\Psr7\Stream:private] => 1
    [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
    [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
        (
        )

)

0 个答案:

没有答案
相关问题