php使用curl發送圖片至接口

  /**
     * 接口調用
     */
    public function query()
    {

        $dir = '/www/root/public/static/img/20190909144840.jpg';  //圖片地址
        $fileInfo = file_get_contents($dir);

        $url = 'http://****************************************'; //接口地址
        $uploadPart = \UploadPart::getInstance($url);
        $res = $uploadPart->putPart([
            'upload'   => $fileInfo,
            'filename' => '20190909144840.jpg',
            'filesize' => filesize($dir)
        ]);

        $res = json_decode($res,true);
        var_dump($res);
    }
class UploadPart
{
    protected static $url;
    protected static $delimiter;
    protected static $instance;

    public function __construct() {
        static::$delimiter = uniqid();
    }

    public function putPart($param) {
        $post_data = static::buildData($param);
        $curl = curl_init(static::$url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Content-Type: multipart/form-data; boundary=" . static::$delimiter,
            "Content-Length: " . strlen($post_data),
            "Version:v1.0",
            "access-token:",
            'Expect:'
        ]);
        $response = curl_exec($curl);
        $curlErrorNo = curl_errno($curl);
        $curlError = curl_error($curl);
        $curlInfoCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        return $response;
    }

    private static function buildData($param){
        $data = '';
        $eol = "\r\n";
        $upload = $param['upload'];
        unset($param['upload']);

        foreach ($param as $name => $content) {
            $data .= "--" . static::$delimiter . "\r\n"
                . 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
                . $content . "\r\n";
        }
        // 拼接文件流
        $data .= "--" . static::$delimiter . $eol
            . 'Content-Disposition: form-data; name="upfile"; filename="' . $param['filename'] . '"' . "\r\n"
            . 'Content-Type:application/octet-stream'."\r\n\r\n";

        $data .= $upload . "\r\n";
        $data .= "--" . static::$delimiter . "--\r\n";
        return $data;

    }
    public static function getInstance($url){
        static::$url = $url;
        if(!self::$instance instanceof self){
            self::$instance = new static();
        }
        return self::$instance;
    }
}
發佈了0 篇原創文章 · 獲贊 14 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章