Board logo

标题: php curl模拟表单上传图片文件 [打印本页]

作者: xiexie    时间: 2020-3-24 19:34     标题: php curl模拟表单上传图片文件

 需要把方法封装到类里,已测试,没问题。 
    public function buildData($param){
        $data = '';
        $eol = "\r\n";
        $upload = $param['file'];
        unset($param['file']);

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

        $data .= $upload . "\r\n";
        $data .= "--" . $this->delimiter . "--\r\n";
        return $data;
    }
    public function post($url, $fields) {
    if(isset($fields['file'])){
    $postData = $this->buildData($fields);
    $header = array(
        "Content-Type: multipart/form-data; boundary=" . $this->delimiter,
            "Content-Length: " . strlen($postData)
        );
    } else {
    $postData = $fields;
    $header = array(
    "Content-Type: multipart/form-data"
        );
    }
        $cl = curl_init();
        if(stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($cl, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($cl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($cl, CURLOPT_URL, $url);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($cl, CURLOPT_POST, TRUE);
        //curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($cl, CURLOPT_POSTFIELDS, $postData);
        $content = curl_exec($cl);
        $status = curl_getinfo($cl);
        curl_close($cl);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            $content = json_decode($content, TRUE);
            return $content;
        } else {
            return array("code"=>"9","message"=>"网络错误");
        }
    }


         $bookCover=file_get_contents("/home/wwwroot/data/book_cv.jpg");
 $bookData['filename']='book_cv.jpg';
 $bookData['type'] = 'image';
 $bookData['filesize'] = 58701; //分片上传
 $bookData['offset'] = 0;
 $bookData['filetype'] = 'image/png';
 $bookData['originName'] = 'book_cv.jpg';
 $bookData['file']= $bookCover;
$returnData=$this->post($this->doMain."push/addBook",$bookData);





欢迎光临 PHP开发笔记 (http://phpvi.com/) Powered by Discuz! 6.1.0