🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ /** * 上传图片到七牛云 */ 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; } ~~~