• php curl form-data上传file方法


    php curl form-data上传file方法

    <?php
    
    
    class UploadPart
    {   
        protected static $url;
        protected static $delimiter;
        protected static $instance;
     
        public function __construct() {
            static::$url = 'http://xx/yasuotupian.php';
            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)
            ]);
            $response = curl_exec($curl);
            curl_close($curl);
     
            return $response;
        }
     
        private static function buildData($param){
            $data = '';
            $eol = "
    ";
            $upload = $param['upload'];
            unset($param['upload']);
     
            foreach ($param as $name => $content) {
                $data .= "--" . static::$delimiter . "
    "
                    . 'Content-Disposition: form-data; name="' . $name . ""
    
    "
                    . $content . "
    ";
            }
            // 拼接文件流
            $data .= "--" . static::$delimiter . $eol
                . 'Content-Disposition: form-data; name="file"; filename="' . $param['filename'] . '"' . "
    "
                . 'Content-Type:application/octet-stream'."
    
    ";
     
            $data .= $upload . "
    ";
            $data .= "--" . static::$delimiter . "--
    ";
            return $data;
        }
     
        public static function getInstance() {
            if(!static::$instance){
                static::$instance = new static();
            }
           return static::$instance;
        }
     
    }
    
    $fields = array(
        'filename' => 'spineboy.png',
        'upload'=>file_get_contents('ss/spineboy.png')
    );
    $part = UploadPart::getInstance()->putPart($fields);
    
    print_r($part);
    exit();

    这个代码是拼接的

  • 相关阅读:
    AC自动机模板
    hdu 6034 贪心模拟 好坑
    UVA 10870
    hdu 2604 递推 矩阵快速幂
    hdu 3117 Fibonacci Numbers 矩阵快速幂+公式
    hdu 1575 Tr A 矩阵快速幂
    POJ_1151 扫描线+离散化+线段树
    HDU_2227 求不减子序列的个数(树状数组+DP)
    深夜敲模板_5——KMP
    深夜敲模板_4——无向图的割顶和桥
  • 原文地址:https://www.cnblogs.com/newmiracle/p/14256031.html
Copyright © 2020-2023  润新知