簡體   English   中英

如何通過PHP CURL(Microsoft Azure API)發送(上傳)文件

[英]How to send (upload) file via PHP CURL (Microsoft Azure API)

我正在嘗試使用Mircosoft Face API檢測圖像中的人臉。

$proxy = 'myProxy';
$img = 'http://example.com/489999.JPG';

$post_string = '{"url":"' . $img . '"}';


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,emotion&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string );


$headers = array();
$headers[] = 'Ocp-Apim-Subscription-Key: ****************';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);

echo "<pre>" .
        json_encode(json_decode($result), JSON_PRETTY_PRINT) . "</pre>";

我的代碼運行良好。 但是我需要使用流上傳而不是提供公共URL來傳遞圖像。 我找到了許多如何做到這一點的例子。 但是我不知道如何將其與我需要發送的其他標頭組合在一起。

我身邊沒有代理,因此我在代碼中將其刪除。 請嘗試下面的代碼,我已經通過了測試,對我有用:

<?php

$imagePath = '<path of your image>';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,emotion&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($imagePath));


$headers = array();
$headers[] = 'Ocp-Apim-Subscription-Key: <sub key >';
$headers[] = 'Content-Type: application/octet-stream';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);

echo "<pre>" .
        json_encode(json_decode($result), JSON_PRETTY_PRINT) . "</pre>";

?>

結果: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM