~~~
/**
* 上傳圖片到七牛云
*/
public function save_ima_remote()
{
$file = request()->file('file');
// 要上傳圖片的本地路徑
$filePath = $file->getRealPath();
$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后綴
// 上傳到七牛后保存的文件名
$key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
// 需要填寫你的 Access Key 和 Secret Key
// 構建鑒權對象
$accessKey = config('qiniu')["accesskey"];
$secretKey = config('qiniu')["secretkey"];
$auth = new Auth($accessKey, $secretKey);
// 要上傳的空間
$bucket = config('qiniu')["bucket"];
//域名
$domain = config('qiniu')["domain"];
$token = $auth->uploadToken($bucket);
// 初始化 UploadManager 對象并進行文件的上傳
$uploadMgr = new UploadManager();
// 調用 UploadManager 的 putFile 方法進行文件的上傳
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
if ($err !== null) {
return ["err" => 1, "msg" => $err, "data" => ""];
} else {
//返回圖片的完整URL
$imgPath = 'http://' . $domain . '/' . $key;
//賦值
return json(['code' => 1, 'url' => $imgPath, 'type' => 1, 'name' => $key]);
}
}
~~~
~~~
/**
* 七牛云刪除圖片
* @param $delFileName 要刪除的圖片文件,與七牛云空間存在的文件名稱相同
* @return bool
*/
public static function delimage($delFileName)
{
// 判斷是否是圖片 目前測試,簡單判斷
$isImage = preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $delFileName);
if (!$isImage) {
return false;
}
$conf = config('qiniu');
// 構建鑒權對象
$auth = new Auth($conf['accesskey'], $conf['secretkey']);
// 配置
$config = new \Qiniu\Config();
// 管理資源
$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
// 刪除文件操作
$res = $bucketManager->delete($conf['bucket'], $delFileName);
if (is_null($res)) {
// 為null成功
return true;
}
return false;
}
~~~
~~~
/**
* 上傳圖片到本地
*/
public function save_img()
{
// 獲取表單上傳文件 例如上傳了001.jpg
$file = request()->file('file');
// 移動到框架應用根目錄/uploads/ 目錄下
$info = $file->move('uploads');
$uploadurl = $info->getSaveName();
//獲取圖片哈希值
$hash = $info->hash('sha1');
//拼接URL
$url = 'http://' . $this->request->host() . '/uploads/' . $uploadurl;
//返回執行結果
$data = ['code' => 1, 'url' => $url, 'type' => 0, 'name' => $uploadurl, 'hash' => $hash];
if ($info) {
return json($data);
} else {
// 上傳失敗獲取錯誤信息
return json(['code' => 0]);
}
}
~~~
~~~
/**
* 刪除本地圖片
*/
public function field_delimage($upload_name)
{
// 判斷是否是圖片 目前測試,簡單判斷
$isImage = preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $upload_name);
if (!$isImage) {
return false;
}
$filename = '../public/uploads/' . $upload_name;
if (file_exists($filename)) {
unlink($filename);
return true;
}
return false;
}
~~~