php使用curl上传图片流到远程服务器

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

    public function __construct() {
        static::$url = 'http://files.note.so/v1/file_server';
        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);
        $info = json_decode($response, true);
        if (!is_array($info['Msg']) && $info['Msg'] == $param['filesize']) {
            $param['offset'] = $param['filesize'];
            $param['upload'] = '';
            return $this->putPart($param);
        }
        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="upload"; 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;
    }

}

调用入口

$fields = array(
    'type' => 'video',
    'filename' => '1407.png',
    'filesize' => 58701,
    'offset' => 0,
    'filetype' => '.acc',
    'originName' => '1407.png',
    'upload'=>file_get_contents('0407.png')//这里可以单独拿出来使用,修改对应的buildData方法就可以直接使用了
);
$part = UploadPart::getInstance()->putPart($fields);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值