來說明怎麼在 CodeIgniter 透過 Imgur API 把檔案傳到 Imgur 上。
首先要在 Imgur 建立一個 Application,而 CodeIgniter 要設定好要上傳的 Controller 和 view。
在使用 upload library 的時候注意上傳的路徑:
$upload_path='./uploads/'; $config['upload_path'] = $upload_path;
因為 imgur API 是抓某個路徑上傳到他們的 server,所以當圖片上傳後,就可以藉由以下的 code 將檔案上傳到 imgur 並取得 URL,這裡我們還會需要 Imgur APP 的 Client ID
$IMGUR_CLIENT_ID = YOUR_IMGUR_CLIENT_ID; if ($this->upload->do_upload('image')) { $data = array('upload_data' => $this->upload->data()); $image_source = file_get_contents($upload_path . $data["upload_data"] ["file_name"]); $postFields = array( 'image' => base64_encode($image_source) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: Client-ID ' . $IMGUR_CLIENT_ID )); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); $response = curl_exec($ch); curl_close($ch); // Decode API response to array $responseArr = json_decode($response); // Check image upload status if (!empty($responseArr ->data ->link)) { $imgurData = $responseArr; var_dump($imgurData); } else { $statusMsg = 'Image upload failed, please try again after some time.'; echo $statusMsg; } }
之後再把需要的值寫到資料庫就好了。
$imgurData 的內容大概會長這樣,可以依需求抓想要的值。
{ "data": { "id": "rwYHrBN", "title": null, "description": null, "datetime": 1649096564, "type": "image/jpeg", "animated": false, "width": 640, "height": 400, "size": 78307, "views": 0, "bandwidth": 0, "vote": null, "favorite": false, "nsfw": null, "section": null, "account_url": null, "account_id": 0, "is_ad": false, "in_most_viral": false, "has_sound": false, "tags": [], "ad_type": 0, "ad_url": "", "edited": "0", "in_gallery": false, "deletehash": "addXM7EZF2UPGlp", "name": "", "link": "https://i.imgur.com/rwYHrBN.jpg" }, "success": true, "status": 200 }
參考:
How to Upload Image to Imgur via API using PHP