2015-01-16 94 views
4

我是初學者到php,我正在通過惠普的IDOL OnDemand API來從任何圖像文件中提取文本。不贊成使用@filename API來上傳文件。請使用CURLFile類代替

我必須設置一個捲曲連接,並執行API請求,但是當我嘗試使用@法發佈文件,在PHP 5.5的已過時,並建議我使用CURLFile。

我也挖PHP手冊,並想出了這樣的事情https://wiki.php.net/rfc/curl-file-upload

守則如下:

$url = 'https://api.idolondemand.com/1/api/sync/ocrdocument/v1'; 

$output_dir = 'uploads/'; 
if(isset($_FILES["file"])){ 

$filename = md5(date('Y-m-d H:i:s:u')).$_FILES["file"]["name"]; 

move_uploaded_file($_FILES["file"]["tmp_name"],$output_dir.$filename); 

$filePath = realpath($output_dir.$filename); 
$post = array(
    'apikey' => 'apikey-goes-here', 
    'mode' => 'document_photo', 
    'file' => '@'.$filePath 
); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
$result = curl_exec($ch); 
curl_close($ch); 
echo $result; 

unlink($filePath); 

如果重寫任何代碼,並告訴我如何使用Curlfile我會很感激。

感謝,

+0

嘿,你可能要停止使用,你在這個問題上張貼的API密鑰,因爲它能有效的公共財產,現在...:/我已經去除了爲你,但它永遠現在在編輯歷史。 (注意:我在惠普工作) –

回答

11

我相信這很簡單,只需將'@'.$filePath改爲使用CurlFile即可。

$post = array('apikey' => 'key', 'mode' => 'document_photo', 'file' => new CurlFile($filePath));

以上爲我工作。

注意:我在惠普工作。

1

由於時間的壓力,我做了一個快速的解決方法時,我整合第三方的API。你可以找到下面的代碼。

$網址:域名和頁面張貼到;例如http://www.snyggamallar.se/en/ $ params:array [key] =值格式,就像你在$ post中一樣。

警告:以@開頭的值將被當作一個文件,這當然是一個限制。這不會導致我的情況有任何問題,但請在代碼中考慮它。

static function httpPost($url, $params){ 
    foreach($params as $k=>$p){ 
     if (substr($p, 0, 1) == "@") { // Ugly 
      $ps[$k] = getCurlFile($p); 
     } else { 
      $ps[$k] = utf8_decode($p); 
     } 
    } 

    $ch = curl_init($url); 
    curl_setopt ($ch, CURLOPT_POST, true); 
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $ps); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 

    $res = curl_exec($ch); 
    return $res; 
} 

static function getCurlFile($filename) 
{ 
    if (class_exists('CURLFile')) { 
     return new CURLFile(substr($filename, 1)); 
    } 
    return $filename; 
} 
相關問題