retful上傳檔案php的實現

來源:互聯網
上載者:User

標籤:

項目中要使用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的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.