美文网首页
php curl上传文件和参数

php curl上传文件和参数

作者: 信仰与初衷 | 来源:发表于2018-09-17 22:17 被阅读0次

1.根据文件路径上传

<?php

$url = "http://localhost/file/upload";
$post_data = array(
  "filename" => "abc.png",
  "bar" => "foo",
  //要上传的本地文件地址
  "file" = > "@/User/www/test/abc.png"
);
$ch = curl_init();
curl_setopt($ch , CURLOPT_URL , $url);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch , CURLOPT_POST, 1);
curl_setopt($ch , CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

上传文件需要用@加上文件的绝对路径

2.根据文件内容上传

<?php

class CurlUploadFile
{   
    protected static $url;
    protected static $delimiter;
    protected static $instance;

    public function __construct() {
        //上传地址
        static::$url = 'http://localhost/file/upload';
        //分割符
        static::$delimiter = uniqid();
    }

    public function putFile($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);
        $info = json_decode($response, true);
        return $response;
    }

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

        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="file"; 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() {
        if(!static::$instance){
            static::$instance = new static();
        }
       return static::$instance;
    }

}

调用上传

$data = array(
    'type' => 'image',
    'filename' => 'abc.png',
    'filesize' => 58701, //分片上传
    'offset' => 0,
    'filetype' => 'image/png',
    'originName' => 'abc.png',
    'file'=>file_get_contents('abc.png')
);
$part = CurlUploadFile::getInstance()->putFile($data);

相关文章

网友评论

      本文标题:php curl上传文件和参数

      本文链接:https://www.haomeiwen.com/subject/lzgdnftx.html