php 特殊场景下post文件


public function genUploadHeaderAndBody($pathInfo, $getParams, $postParams, $filePath, $uploadNameField = 'file') {
    if (!file_exists($filePath) || empty(filesize($filePath))) {
        return false;
    }

    $delimiter = '------------------' . uniqid();

    $body = self::genPostBody($delimiter, $postParams, $filePath, $uploadNameField);

    $header = array(
        'pathinfo' => $pathInfo,
        'querystring' => http_build_query($getParams),
        'Content-Type' => 'multipart/form-data; boundary=' . $delimiter,
        'Content-Length' => strlen($body),
    );

    return array(
        'header' => $header,
        'body' => $body,
    );
}

private function genPostBody($delimiter, $postParams, $filePath, $uploadNameField) {
    $fp = fopen($filePath, 'r');
    $fileContent = fread($fp, filesize($filePath));
    fclose($fp);

    $data = '';
    $eol = "\r\n";

    // 拼接post参数
    foreach ($postParams as $key => $value) {
        $data .= '--' . $delimiter . "\r\n";
        $data .= 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n";
        $data .= $value . "\r\n";
    }

    // 拼接文件流
    $data .= '--' . $delimiter . "\r\n";
    $data .= 'Content-Disposition: form-data; name="' . $uploadNameField . '"; filename="' . basename($filePath) . "\"\r\n";
    $data .= 'Content-Type: application/octet-stream' . "\r\n\r\n";
    $data .= $fileContent . "\r\n";
    $data .= '--' . $delimiter . '--' . "\r\n";
    return $data;
}



public function execute(){
    $pathInfo = '/filecenter/file/upload/';

    $getParams = array(
        'tpl'   => 6,
        'cuid'  => 'activitycuid',
    );

    $filePath = '/home/zbl/data/z1.jpg';

    $postParams = array(
        'is_public'   => 1,
        'extension'   => 'jpg',
        'mcs_channel' => 'thumbnail',
        'md5'         => md5_file($filePath),
    );

    $getParams['sign'] = 'xxxxxxx';

    $req = self::genUploadHeaderAndBody($pathInfo, $getParams, $postParams, $filePath, 'file');

    if (!$req) {
        echo "error on genUploadHeaderAndBody";
        return;
    }

    $rst = curl('MobileToolsService', 'post', $req['body'], '', $req['header']);

    if ($rst) {
        echo $rst;
    }
    else {
        var_dump($rst);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容