zoukankan      html  css  js  c++  java
  • retful上传文件php的实现

    项目中要使用restful上传文件到服务器,一直不能成功,后生成相关串后在postman中上传成功,利用这个工具生成php curl的代码,后逐步比对产生以下代码。   

    /**
         * 上传文件
         * @param unknown $filename
         */
        function fileUpload($filename,$type)
        {
            $serviceName='imageup';
            $contents = file_get_contents($filename);
            //content boundary
            $boundary   = md5(time());
            $postStr  = "";
            $postStr .="-----".$boundary." ";
            $postStr .="Content-Disposition: form-data; name="file"; filename="".$filename."" ";
            $postStr .="Content-Type: jpg ";     
            $postStr .=$contents." ";
            $postStr .="-----".$boundary."--";
           
            $timestamp=$this->getMillisecond();
            $signstr=$this->sign('', $timestamp, $this->prikey);
            $post_data=array("v"=>$this->ver,
                "ts"=>$timestamp,
                "sign"=>$signstr,
                "user"=>$this->userSn
            );
            $o = "";
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
            $timeout = 30;      
            $postUrl = $this->url_province.$serviceName."/".$type."/" .'?' . $post_data;
           
            $ch = curl_init();
            $boundary = md5(time());
            curl_setopt_array($ch, array(
                CURLOPT_URL => $postUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 300,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $postStr,
                CURLOPT_HTTPHEADER => array(
                    "cache-control: no-cache",
                    "content-type: multipart/form-data; boundary=---".$boundary,
                ),
            ));
            $result = curl_exec($ch);
            curl_close($ch);
     
            return $result;              
        }

    $boundary 的格式不能改变,“-----”、“ "上面程序已经过测试

  • 相关阅读:
    阿里云“网红"运维工程师白金:做一个平凡的圆梦人
    3235 战争
    1291 火车线路(区间修改,区间最值)
    P3183 [HAOI2016]食物链
    P1189 SEARCH(逃跑的拉尔夫)
    P1794 装备运输_NOI导刊2010提高(04)
    P2347 砝码称重
    P1332 血色先锋队
    P1772 [ZJOI2006]物流运输
    P1038 神经网络
  • 原文地址:https://www.cnblogs.com/xihong2014/p/5894294.html
Copyright © 2011-2022 走看看