码迷,mamicode.com
首页 > Web开发 > 详细

PHP中以multipart/form-data上传文件流

时间:2018-06-07 11:28:53      阅读:2389      评论:0      收藏:0      [点我收藏+]

标签:Curl   multipart/form-data   

上传类
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‘)
);
$part = UploadPart::getInstance()->putPart($fields);

PHP中以multipart/form-data上传文件流

标签:Curl   multipart/form-data   

原文地址:http://blog.51cto.com/suiwnet/2125883

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!