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 的格式不能改变,“-----”、“ "上面程序已经过测试

  • 相关阅读:
    常用的android弹出对话框
    Android 启动后台运行程序(Service)
    java 日期获取时间戳
    stringbuffer与stringbuilder的区别
    Linux记录-sysctl.conf优化方案
    Linux记录-salt分析
    Hadoop记录-fair公平调度队列管理
    Linux记录-GC分析
    Hadoop记录-hdfs转载
    Linux记录-salt-minion安装
  • 原文地址:https://www.cnblogs.com/xihong2014/p/5894294.html
Copyright © 2011-2022 走看看