“指定的内容类型无效”;上传文件到Apigility时


"Invalid content-type specified" when uploading file to Apigility

我正在使用Zend Framework 2和Zend Framework的Apigility构建RPC API。为了测试,我使用了chrome扩展Postman REST-Client。

我可以做POST请求没有问题,当我使用邮差。但是我的代码不工作。

$client = new 'Zend'Http'Client();
$client->setUri($uri)
        ->setMethod('POST')
        ->setParameterPost(
            array(
                'file' => '/home/user/Downloads/file.csv'
            )
        );
$headers = new 'Zend'Http'Headers();
$headers->addHeaders(array(
    'Accept' => 'application/json;',
));
$client->setHeaders($headers);
$client->setStream();
$response = $client->send();
$file = '/home/user/Downloads/file.csv';
$file2 = '/home/user/Downloads/file2.csv';
copy($response->getStreamName(), $file);
$fp = fopen($file2, "w");
stream_copy_to_stream($response->getStream(), $fp);
$client->setStream($file);
$responce = $client->send();
echo $responce->getBody();

我试图传递其他标头Content-Type,但它导致致命错误。我需要传递头使其工作吗?

您必须将Content-Type标头设置为multipart/form-data。你在Chrome中使用的Postman插件会自动为文件上传执行此操作。

所以像这样设置标题:

$headers->addHeaders(array(
    'Accept' => 'application/json',
    'Content-Type' => 'multipart/form-data'
));

如果这不起作用,请更具体地说明你得到的致命错误