【问题标题】:How to POST binary data using cURL in PHP?如何在 PHP 中使用 cURL 发布二进制数据?
【发布时间】:2021-01-15 10:54:16
【问题描述】:

使用 Microsoft Azure OCR,我只能在回复中得到文字。这对我来说是个问题,因为我需要获取数值(部分代码)。 Read API 文档真的很差,我不知道如何在 PHP 中使用 cURL 发送我的二进制数据文件。

在 OCR (https://westeurope.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/56f91f2e778daf14a499f20d/console) 中,这将是请求:

POST https://westeurope.api.cognitive.microsoft.com/vision/v3.1/ocr?language=unk&detectOrientation=true HTTP/1.1
Host: westeurope.api.cognitive.microsoft.com
Content-Type: multipart/form-data

[Binary image data]

在 PHP 中,我的代码如下所示:

$mime = mime_content_type($files['tmp_name']);
$postfields = array('image' => new CURLFile($files['tmp_name'], $mime, $files['name']));
            
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$ocr_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data', 
                'Ocp-Apim-Subscription-Key: '.$ocr_key
            ));
$result = curl_exec($ch);
curl_close($ch);

这适用于 OCR,但是当我想使用读取 API 时,multipart/form-data 不是作为内容类型的选项。更改 Read API 中的内容类型(当然还有 URL)也无济于事。我已经尝试了几种方法。 阅读 API 文档:https://westeurope.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-1-ga/operations/5d986960601faab4bf452005

请问有谁可以帮帮我吗?

【问题讨论】:

  • 您好,您应该重新表述您的问题并添加有关您的确切问题的更多详细信息。在这里,您混合了有关 OCR 与读取的详细信息,我们不清楚您在哪里被阻止以及您到目前为止尝试了什么

标签: curl http-post binary-data php-curl azure-cognitive-services


【解决方案1】:

这是读取 API 的link 到 PHP 代码,支持的正文输入方法:原始图像二进制或图像 URL。

<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://westeurope.api.cognitive.microsoft.com/vision/v3.1/read/analyze');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Content-Type' => 'application/json',
    'Ocp-Apim-Subscription-Key' => '{subscription key}',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
    'language' => '{string}',
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_POST);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多