首頁 >後端開發 >php教程 >curl上傳圖片向api失敗

curl上傳圖片向api失敗

WBOY
WBOY原創
2016-08-18 09:16:351064瀏覽

<code>   <?php
   function upload_file($url,$filename,$path,$type){
        $data = array(
            'access_token' => '**************',
            'status' => 'img',
            'visible'=>1,
            'pic'=>'@'.realpath($path).";type=".$type.";filename=".$filename
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $return_data = curl_exec($ch);
        curl_close($ch);
        $decode = json_decode($return_data);
        echo $decode->original_pic;       
   }

    if ($_POST) {
        $url = 'https://upload.api.weibo.com/2/statuses/upload.json';
        $path = $_SERVER['DOCUMENT_ROOT'];
        $tmpname = $_FILES['fname']['name'];
        $tmpfile = $_FILES['fname']['tmp_name'];
        $tmpType = $_FILES['fname']['type'];
        upload_file($url,$tmpname,$tmpfile,$tmpType);
        exit;
    }
    echo '<form action="" enctype="multipart/form-data"  method="post">
    <input type="file" name="fname" /》
    <input type="submit" value="Submit" />
    </form>';
?>
</code>

頁面沒有報錯訊息,而且我打開微博的api顯示405錯誤,不知道是不是api本身的原因。

回覆內容:

<code>   <?php
   function upload_file($url,$filename,$path,$type){
        $data = array(
            'access_token' => '**************',
            'status' => 'img',
            'visible'=>1,
            'pic'=>'@'.realpath($path).";type=".$type.";filename=".$filename
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $return_data = curl_exec($ch);
        curl_close($ch);
        $decode = json_decode($return_data);
        echo $decode->original_pic;       
   }

    if ($_POST) {
        $url = 'https://upload.api.weibo.com/2/statuses/upload.json';
        $path = $_SERVER['DOCUMENT_ROOT'];
        $tmpname = $_FILES['fname']['name'];
        $tmpfile = $_FILES['fname']['tmp_name'];
        $tmpType = $_FILES['fname']['type'];
        upload_file($url,$tmpname,$tmpfile,$tmpType);
        exit;
    }
    echo '<form action="" enctype="multipart/form-data"  method="post">
    <input type="file" name="fname" /》
    <input type="submit" value="Submit" />
    </form>';
?>
</code>

頁面沒有報錯訊息,而且我打開微博的api顯示405錯誤,不知道是不是api本身的原因。

如果php的版本是5.5以上
用curl上傳檔案時不能用@+檔案路徑的方式了.
要用CURLFile來代替, 就算curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); 也沒有用

設定一下協定試試看呢! header("Content-Type:multipart/form-data")

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn