PHP使用curl上传文件到远程服务器接口

2023-04-25 21:37:40

该篇已同步发表于个人博客 https://qiucode.cn/article/94

当然你的php.ini开启了curl扩展功能

1、文件上传

  /**
     * 以文件上传  第二种方法
     */
    public function upload(){
        $result = array('code' => 0, 'message' => 'ok');
        ini_set('upload_max_filesize', '20M');
        ini_set('post_max_size', '20M');
        ini_set('memory_limit', '128M');

        $url="http://xx.xx.xx.xx/api/file/upload";  //远程接口地址

        $file = $_FILES['file'];

        if ($file['error'] != 0) {
            $result['code'] = 40001;
            $result['message'] = '上传出错';
            $this->error();  //使用Thinkphp5.1内置controller方法
        } else {
            $filename = $file['name'];
            $tmpfile = $file['tmp_name'];
            $filetype = $file['type'];
            $data = self::upload_file($url, $filename, $tmpfile, $filetype);

            $data = json_decode($data,true);
            $this->success(); 使用Thinkphp5.1内置controller方法
            die;
        }
    }

 /**
  * curl上传文件
  * 
  * @param unknown $url
  * @param unknown $filename
  * @param unknown $path
  * @param unknown $type
 */
 protected function upload_file($url,$filename,$path,$type){
        //php 5.5以上的用法
    if (class_exists('\CURLFile')) {
       $data = array('file' => new \CURLFile(realpath($path),$type,$filename));
    } else {
       $data = array(
           'file'=>'@'.realpath($path).";type=".$type.";filename=".$filename
          );
    }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, true );
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $return_data = curl_exec($ch);
     curl_close($ch);
     echo $return_data;
    }

2、文件接收端(不限定于PHP)

 /**
   * 接收文件
  */
public function upload(){
    Log::info('--------------$_FILES--------------------');
    Log::info($_FILES);
    if( $_FILES){
        $filename = $_FILES['file']['name'];
        $tmpname = $_FILES['file']['tmp_name'];
        if(move_uploaded_file($tmpname,  $_SERVER['DOCUMENT_ROOT']."/excel-file/" .$filename)){
            echo json_encode('上传成功');
        }else{
            $data = json_encode($_FILES);
            echo $data;
        }
    }   
 }

3、以下是以二进制文件上传偶尔会失败,故而不推荐使用,在此记录下!

 /**
  * 以二进制文件上传
  */
 public function upload_stream(){

     $url="http://xx.xx.xx.xx/api/file/upload";  //上传远程接口地址
     $info = $_FILES['file'];
     $fp = fopen($info['tmp_name'], 'r');
     $filebinary = fread($fp, filesize($info['tmp_name']));
     fclose($fp);

     $opts = array(
         'http' => array(
             'method' => 'POST',
             'header' => 'content-type:application/x-www-form-urlencoded',
             'context' =>  $filebinary 
         )
     );

     $context = stream_context_create($opts);
     $response = file_get_contents($url, false, $context); //就是这个方法  偶尔会失败哦!
     $ret = json_decode($response, true);
     return $ret['success'];

 }

//以下服务部署于服务端(不限定于PHP)
 /**
  * 接收二进制流文件
 */
public function upload_stream(){

    $streamData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ?                                          $GLOBALS['HTTP_RAW_POST_DATA'] : '';

    $receiveFile =  $_SERVER['DOCUMENT_ROOT']."/excel-file/receiv.xlsx";

    if(empty($streamData)){
        $streamData = file_get_contents('php://input');
    }

    if($streamData!=''){
        $ret = file_put_contents($receiveFile, $streamData, true);
    }else{
        $ret = false;
    }

    return $ret;
}

  • 作者:甄齐才
  • 原文链接:https://blog.csdn.net/coco2d_x2014/article/details/115599555
    更新时间:2023-04-25 21:37:40