PHP:一次上传多个图像到imgur

时间:2013-11-14 12:41:18

标签: php api imgur

我有以下代码,它可以很好地使用他们的API将一个图像上传到Imgur:

$client_id = $myClientId;
    $file = file_get_contents($_FILES["file"]["tmp_name"]);

    $url = 'https://api.imgur.com/3/image.json';
    $headers = array("Authorization: Client-ID $client_id");
    $pvars = array('image' => base64_encode($file));

    $curl = curl_init();

    curl_setopt_array($curl, array(
       CURLOPT_URL=> $url,
       CURLOPT_TIMEOUT => 30,
       CURLOPT_POST => 1,
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_HTTPHEADER => $headers,
       CURLOPT_POSTFIELDS => $pvars
    ));

    $json_returned = curl_exec($curl); // blank response

    $json = json_decode($json_returned, true);

    curl_close ($curl); 

但是我需要一次上传多张图片。在客户端,用户将有多个<input type="file" />字段。我现在完全陷入困境,弄清楚我需要修改此代码的位置和方式,以便在以阵列形式进入服务器时处理多个图像上传。有没有人有任何想法?

1 个答案:

答案 0 :(得分:3)

更改标记如下:

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="file[]" type="file" multiple="multiple" /><br />
  <input type="submit" value="Send files" />
</form>

现在,您可以使用$_FILES遍历foreach数组,如下所示:

foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
    if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
    {
        // $tmpName is the file
        // code for sending the image to imgur
    }
}