retful上传文件php的实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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."\r\n";
        $postStr .="Content-Disposition: form-data; name=\"file\"; filename=\"".$filename."\"\r\n";
        $postStr .="Content-Type: jpg\r\n\r\n";     
        $postStr .=$contents."\r\n";
        $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 的格式不能改变,“-----”、“\r\n"上面程序已经过测试

以上是关于retful上传文件php的实现的主要内容,如果未能解决你的问题,请参考以下文章

怎样用PHP实现文件上传

求php怎么实现web端上传超大文件

php如何实现一次性上传多个文件

php多文件上传实现代码

如何实现用php上传视频文件?

php 文件上传