七牛云是一個便捷的數據云存儲平臺。通過官方或社區社區SDK你可以方便通過程序上傳文件到自己的空間中。下面的這個小 Demo 是通過 七牛官方 PHP-SDK 將一個網上的圖片url 上傳到自己的七牛 Bucket 中。這個 Demo 的關鍵點是使用 curl 讀取圖片內容,然后在將讀取的圖片內容通過指定 MIME 上傳到指定 Bucket 即可。
- 安裝 七牛云 PHP-SDK
git clone https://github.com/qiniu/php-sdk.git
- Demo 的文件結構
image
- Demo 代碼
<?php
require_once __DIR__ . './autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class uploadImage {
public $access_key;
public $secret_key;
public $bucket;
public function __construct()
{
$this->access_key = '填寫你的七牛云 access_key';
$this->secret_key = '填寫你的七牛云 secret_key';
$this->bucket = '填寫你的七牛云 bucket';
}
/*
* @ 上傳遠端圖片
* @ 2017/10/09
* @ 雨醉風塵
* */
public function uploadImg($imgUrl)
{
#讀取網上圖片內容
$imageData = self::getImgData($imgUrl);
$auth = new Auth($this->access_key, $this->secret_key);
$token = $auth->uploadToken($this->bucket);
#上傳的文件名
$key = 'imgUrl_'.microtime(true).'.jpg';
$up = new UploadManager();
$mime = 'image/jpeg';
list($rest, $err) = $up->put($token, $key, $imageData, null, $mime);
if ($err) {
echo '<pre>';
print_r($err);
} else {
echo '<pre>';
print_r($rest);
$domain = '上傳 Bucket 外鏈默認';
#獲取上傳到七牛云的圖片url
$uploadUrl = $domain.$rest['key'];
echo "<img src=$uploadUrl>"; //圖片顯示
}
}
protected function getImgData($imgUrl)
{
$ch = curl_init($imgUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
//讀取圖片信息
$rawData = curl_exec($ch);
curl_close($ch);
//讀取文件到本地
//file_put_contents('aa.png',$rawData);
return $rawData;
}
}
$upTest = new uploadImage();
$uploadImageUrl = "http://s3.cn.bing.net/th?id=OJ.z0O2eyRKKpwmZQ&pid=MSNJVFeeds";
$upTest->uploadImg($uploadImageUrl);
- 程序執行結果
image
- 在 七牛云 后臺查看 是否存在
imgUrl_1507562883.5045.jpg
文件
image