PHP访问REST API上传文件的解决方案

最近写的一个小功能需要通过rest方式上传文件,因此就在网上找了一些解决方案。接下来说明以下我采用的解决方案:

我是利用curl来实现的,其中CURLOPT_POST的值为TRUE代表的是请求类型为POST请求,CURLOPT_POSTFIELDS定义要传递的值,下面是我的curl类:

 1 <?php
 2 class Curl{
 3     protected $uri = '';
 4     protected $hr = null;
 5     
 6     public function __construct($uri)
 7     {
 8         $this->uri = $uri;
 9         
10         $this->hr = curl_init();
11 
12         curl_setopt($this->hr, CURLOPT_RETURNTRANSFER, true);
13         curl_setopt($this->hr, CURLOPT_URL, $this->uri);
14     }
15 
16     public function post($data = array(),$param = array()) {
17         if(empty($data))
18         {
19             return FALSE;
20         }
21         
22         $opts = array(
23             CURLOPT_POST    => true,
24             CURLOPT_POSTFIELDS => $data
25         );
26         
27         if(!empty($param))
28         {
29             curl_setopt($this->hr,CURLOPT_HTTPHEADER,array("params:".http_build_query($param)));
30         }
31         
32         curl_setopt_array($this->hr, $opts);
33         $content = curl_exec($this->hr);
34         $status = curl_getinfo($this->hr, CURLINFO_HTTP_CODE);
35         $content_type = curl_getinfo($this->hr, CURLINFO_CONTENT_TYPE);
36 
37         echo $content;
38     }
39 }
40 ?>

ps:这里我主要说的是上传文件,因此curl类中我也只定义了post方法。

接下来是我调用curl的post类上传图片的上传页面:

 1 <?php
 2 require_once 'curl.php';
 3 
 4     if(isset($_FILES['file']) && !empty($_FILES['file']))
 5     {
 6         $file = $_FILES['file'];
 7         
 8         $newFile = './'.$file['name'];
 9 
10         //复制文件到上传目录
11         move_uploaded_file($file['tmp_name'], $newFile);
12         
13         $curl = new Curl('http://xxxx/testCurl/post.php');
14         
15         $data = array(
16             'pic'=>"@D:/www/testCurl/".$file['name'],
17             'id'=>"1"
18         );
19         
20         $curl->post($data);
21         }else{
22 ?>
23 <html>
24 <head></head>
25 <body>
26 <form method='post' enctype="multipart/form-data">
27 <input type="file" name="file">
28 <button type="submit">上传</button>
29 </form>
30 </body>
31 </html>
32 <?php
33     }
34 ?>

ps:定义传递数据时,加@符号表示是上传文件,@后的文件路径需要是绝对路径。

在rest端只需要使用$_FILES就可以接收到上传的文件了,处理方式与普通上传的处理方式相同。