laravel提供了方便快捷的文件操作,与遇到第三方文件服务器,例如阿里云,七牛云等等如何处理上传的文件,下面案例是使用七牛云案例。
在laravel使用:
?
1,首先我们需要下载七牛云sdk,定义qiniuyun类库,具体一些配置就不写了,相信使用过第三方文件服务器工具都应该知道原理,如下
<?php
namespace Services;
use Illuminate\Support\Facades\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
class Qiniu {
?
? ? //访问 key
? ? private $accessKey;
?
? ? //密钥
? ? private $secretKey;
?
? ? private $bucket;
?
? ? private $token;
?
? ? private $err;
?
? ? private $ret;
?
? ? /**
? ? ?* @var array 七牛域名 绑定
? ? ?*/
? ? private $qiniu_domain = array(
? ? ? ? ‘product-images‘ => ‘https://dn-yidd-product-images.qbox.me‘,
? ? ? ? ‘article-images‘ => ‘https://dn-yidd-article-images.qbox.me‘,
? ? ? ? ‘avator-images‘ => ‘https://dn-yidd-avator-images.qbox.me‘,
? ? ? ? ‘drugstore-images‘ => ‘https://dn-yidd-drugstore-images.qbox.me‘,
? ? ? ? ‘id-images‘ => ‘https://dn-yidd-id-images.qbox.me‘,
? ? ? ? ‘ue-images‘ => ‘https://dn-yidd-ue-images.qbox.me‘,
? ? ? ? ‘topic-images‘ => ‘https://dn-yidd-topic-images.qbox.me‘,
? ? ? ? ‘slide-images‘ => ‘https://dn-ydd-slide-images.qbox.me‘,
? ? ? ? ‘test-paper-images‘ => ‘https://dn-ydd-test-paper-images.qbox.me‘,
? ? ? ? ‘event-images‘ => ‘https://dn-yidd-event-images.qbox.me‘,
? ? ? ? ‘audio‘ => ‘https://dn-yidd-audio.qbox.me‘,
? ? ? ? ‘video‘ => ‘https://dn-yidd-video.qbox.me‘,
? ? ? ? ‘group-images‘ => ‘https://dn-yidd-group-images.qbox.me‘,
? ? );
?
? ? /**
? ? ?* @param $bucket 七牛空间名称
? ? ?* @param bool $require_auth 是否需要权限
? ? ?*/
? ? public function __construct($bucket,$require_auth = false){
?
? ? ? ? $this->bucket = $bucket;
? ? ? ? if($require_auth){
? ? ? ? ? ? $this->accessKey = Config::get(‘config.access_key‘);
? ? ? ? ? ? $this->secretKey = Config::get(‘config.secret_key‘);
? ? ? ? ? ? $this->auth = new Auth($this->accessKey, $this->secretKey);
? ? ? ? ? ? $this->token = $this->auth->uploadToken($this->bucket);
? ? ? ? }
? ? }
?
?
? ? /**
? ? ?* @param $key 唯一存储名称
? ? ?* @param $filePath 本地上传文件路径
? ? ?*/
? ? public function upload($key, $filePath){
? ? ? ? $uploadMgr = new UploadManager();
? ? ? ? list($ret, $err) = $uploadMgr->putFile($this->token, $key, $filePath);
? ? ? ? if ($err !== null) {
? ? ? ? ? ? $this->err = $err;
? ? ? ? } else {
? ? ? ? ? ? $this->ret = $ret;
? ? ? ? ? ? $this->DeleteLocalImage($filePath);
? ? ? ? ? ? return true;
? ? ? ? }
? ? }
?
? ? /**
? ? ?* 删除
? ? ?* 唯一存储名称
? ? ?* @param $key
? ? ?*/
? ? public function delete($key){
? ? ? ? $bucketMgr = new BucketManager($this->auth);
? ? ? ? $err = $bucketMgr->delete($this->bucket, $key);
? ? ? ? if ($err !== null) {
? ? ? ? ? ? return false;
? ? ? ? } else {
? ? ? ? ? ? return true;
? ? ? ? }
? ? }
?
? ? /**
? ? ?* @param $key 唯一存储名称
? ? ?* @return string
? ? ?*/
? ? public function getFileUrl($key){
? ? ? ? return $this->qiniu_domain[$this->bucket].‘/‘.$key;
? ? }
?
? ? /*
? ? ?* 获取存储空间https地址
? ? ?*
? ? ?*/
? ? public function getDomain(){
? ? ? ? return $this->qiniu_domain[$this->bucket].‘/‘;
? ? }
?
? ? /**
? ? ?* 获取 token
? ? ?* @return string
? ? ?*/
? ? public function getToken(){
? ? ? ? return $this->token;
? ? }
?
? ? /**
? ? ?* 返回错误
? ? ?* @return mixed
? ? ?*/
? ? public function getErr(){
? ? ? ? return $this->err;
? ? }
?
? ? /**
? ? ?* 返回七牛返回值
? ? ?* @return mixed
? ? ?*/
? ? public function getReturn(){
? ? ? ? return $this->ret;
? ? }
?
? ? //删除本地图片
? ? public function DeleteLocalImage($filePath){
? ? ? ? $result = @unlink ($filePath);
? ? ? ? return $result;
? ? }
}
?
2,定义生成七牛云文件的命名规则的类库
<?php
namespace App\Services;
class Util{
? ? private static $_instance;
? ? public static function getUtilData(){
? ? ? ? if(!self::$_instance){
? ? ? ? ? ? self::$_instance = new Util();
? ? ? ? }
? ? ? ? return self::$_instance;
? ? }
?
? ? /**
? ? ?* ?七牛文件命令规则
? ? 1. 身份证:id_用户ID_时间戳.png
? ? 2. 头像:avatar_用户ID_时间戳.png
? ? 3. 药店营业执照:bl_药店名称_时间戳.png
? ? 4. 产品图片:product_产品ID_时间戳.png
? ? 5. 文章列表图片:artile_文章ID_时间戳.png
? ? ?*
? ? ?* ?* $id = 数据编号
? ? ?* $type = 所代表的空间名称
? ? ?*
? ? ?*
? ? ?* 4【‘product‘=>‘产品图片‘】id必传
? ? ?* 5【‘article‘=>‘文章图片‘】id必传
? ? ?* 8【‘slide‘=>‘幻灯片‘】 id 非必传
? ? ?* 9【‘test_paper‘=>‘题卷图片‘】 id 必传
? ? ?* 10【‘event‘=>‘活动图片‘】id必传
? ? ?*
? ? ?*
? ? ?* @param $bucketType
? ? ?* @param intval $id
? ? ?* @param string $filename
? ? ?* @return string
? ? ?*/
?
? ? public function create_qiniu_unqiue_name($bucketType,$id=false,$filename = ‘‘){
? ? ? ? $arr = [1=>‘id‘,2=>‘avator‘,3=>‘drugstore‘,4=>‘product‘,5=>‘article‘,8=>‘slide‘,9=>‘test_paper‘,10=>‘event‘];
? ? ? ? $name = $arr[$bucketType] ? $arr[$bucketType] : false;
? ? ? ? if($name === false){
? ? ? ? ? ? return false;
? ? ? ? }
? ? ? ? if($id === false){
? ? ? ? ? ? $file_prefix = ?$name.‘_‘;
? ? ? ? }else{
? ? ? ? ? ? $file_prefix = $name.‘_‘.$id.‘_‘;
? ? ? ? }
? ? ? ? $ext = ‘‘;
? ? ? ? if($filename != ‘‘){
? ? ? ? ? ? $ext = substr($filename,strrpos($filename,‘.‘));
? ? ? ? }
? ? ? ? list($u, $s) = explode(‘ ‘,microtime());
? ? ? ? $s = date(‘ymdhis‘,$s);
? ? ? ? $result = $s.($u* pow(10,2));
? ? ? ? if(strpos($result,‘.‘)){
? ? ? ? ? ? list($result,$useless) = explode(‘.‘,$result);
? ? ? ? }
? ? ? ? $name = $file_prefix.$result.$this->getRandCode(6);
? ? ? ? return $name.$ext;
? ? }
?
? ? /**
? ? ?* ?七牛文件命令规则 ---javascript web 上传命名规则
? ? 1. 身份证:id_用户ID_时间戳.png
? ? 2. 头像:avatar_用户ID_时间戳.png
? ? 3. 药店营业执照:bl_药店名称_时间戳.png
? ? 4. 产品图片:product_产品ID_时间戳.png
? ? 5. 文章列表图片:artile_文章ID_时间戳.png
? ? ?*
? ? ?* ?* $id = 数据编号
? ? ?* $type = 所代表的空间名称
? ? ?*
? ? ?*
? ? ?* 4【‘product‘=>‘产品图片‘】id必传
? ? ?* 5【‘article‘=>‘文章图片‘】id必传
? ? ?* 8【‘slide‘=>‘幻灯片‘】 id 非必传
? ? ?* 9【‘test_paper‘=>‘题卷图片‘】 id 必传
? ? ?* 10【‘event‘=>‘活动图片‘】id必传
? ? ?* 13【‘group‘=>‘群组头像‘】id必传
? ? ?*
? ? ?*
? ? ?* @param $bucketType
? ? ?* @param intval $id
? ? ?* @param string $filename
? ? ?* @return string
? ? ?*/
?
? ? public function javascript_create_qiniu_unqiue_name($bucketType,$id=false){
? ? ? ? $arr = [4=>‘product‘,5=>‘article‘,8=>‘slide‘,9=>‘test_paper‘,10=>‘event‘,13=>‘group‘];
? ? ? ? $name = $arr[$bucketType] ? $arr[$bucketType] : false;
? ? ? ? if($name === false){
? ? ? ? ? ? return false;
? ? ? ? }
? ? ? ? if($id === false){
? ? ? ? ? ? $file_prefix = ?$name.‘_‘;
? ? ? ? }else{
? ? ? ? ? ? $file_prefix = $name.‘_‘.$id.‘_‘;
? ? ? ? }
? ? ? ? list($u, $s) = explode(‘ ‘,microtime());
? ? ? ? $s = date(‘ymdhis‘,$s);
? ? ? ? $result = $s.($u* pow(10,2));
? ? ? ? if(strpos($result,‘.‘)){
? ? ? ? ? ? list($result,$useless) = explode(‘.‘,$result);
? ? ? ? }
? ? ? ? return $file_prefix.$result.$this->getRandCode(6);
? ? }
?
? ? /**
? ? ?* 获取直定长度随机码
? ? ?* @param type $length
? ? ?* @param type $type 0 纯数字 1 数字、小写字母 2 数字、小写字母、大写字母
? ? ?* @return string
? ? ?*/
? ? function getRandCode($length = 6,$type = 0)
? ? {
? ? ? ? if($type == 0) {
? ? ? ? ? ? $str = ‘0123456789‘;
? ? ? ? }else if($type == 1){
? ? ? ? ? ? $str = ‘0123456789abcdefghijklmnopqrstuvwxyz‘;
? ? ? ? }else{
? ? ? ? ? ? $str = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘;
? ? ? ? }
? ? ? ? $len = strlen($str);
? ? ? ? $retStr = ‘‘;
? ? ? ? for($i=0;$i<$length;$i++){
? ? ? ? ? ? $retStr .= $str[rand(0, $len-1)];
? ? ? ? }
? ? ? ? return $retStr;
? ? }
}
?
3,好了,工具已经准备好了,我们开始吧,首先是新建一个html文件,当然laravel路由配置需要自己配置,在app\http\route.php中配置:
例如Route::any(‘User/add‘,[‘middleware‘=>‘auth‘,‘uses‘=>‘Backstage\User\UserController@add‘]);//新增会员
html中部分内容:
<form id="frm_add" name="frm_add" class="formbody" action="{{url(‘User/add‘)}}" method="post" enctype="multipart/form-data">
......
<li>
? ?<span>头像</span>
? ? ? ? ?<cite><input id="avatar" name="avatar" type="file"></cite>
?</li>
.......
</form>
form提交过后,注:前端上传文件未做文件大小,类型作验证,有兴趣的,自己作验证,这里就在后端通过php代码进行验证了。
php代码:
public function add(Request $request){
? ? ? ? $userLogic = new \App\Logics\UserLogic();
? ? ? ? if($request->isMethod(‘post‘)){
? ? ? ? ? ? $temp_name = ‘‘;
? ? ? ? ? ? $avatar_upload_path = ‘‘;
? ? ? ? ? ? $path = "";
? ? ? ? ? ? if($request->hasFile(‘avatar‘)){
? ? ? ? ? ? ? ? $avatar = $request->file(‘avatar‘);
? ? ? ? ? ? ? ? //get avatar config para
? ? ? ? ? ? ? ? $avatar_config = config(‘config.avatar‘);
? ? ? ? ? ? ? ? if(!in_array(strtolower($avatar->getClientOriginalExtension()),$avatar_config[‘extension‘])){
? ? ? ? ? ? ? ? ? ? show_message(‘上传文件格式错误,请重新上传!‘,‘goback‘,1000,0);exit;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if($avatar->getSize() > $avatar_config[‘size‘]){
? ? ? ? ? ? ? ? ? ? show_message(‘上传文件过大,请上传不超过2M的文件!‘,‘goback‘,1000,0);exit;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? $filesystem = new Filesystem();
? ? ? ? ? ? ? ? $avatar_upload_path = public_path() . ‘/upload/avatar/‘;
? ? ? ? ? ? ? ? if(!$filesystem->exists($avatar_upload_path) || !$filesystem->isWritable($avatar_upload_path)){
? ? ? ? ? ? ? ? ? ? $filesystem->makeDirectory($avatar_upload_path, 0755, false, true);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? $temp_name = md5(\Carbon\Carbon::now()->timestamp.$avatar->getClientOriginalName()).‘.‘.$avatar->getClientOriginalExtension();
? ? ? ? ? ? ? ? //move uploaded file to fixed public directory
? ? ? ? ? ? ? ? $path = $avatar->move($avatar_upload_path,$temp_name);
? ? ? ? ? ? }
? ? ? ? ? ? if(!empty($insertGetId = $userLogic->insertUser($request))){
? ? ? ? ? ? ? ? if(!empty($temp_name) && !empty($avatar_upload_path) && $filesystem->exists($avatar_upload_path.$temp_name)){
? ? ? ? ? ? ? ? ? ? $utilService = new \App\Services\Util();
? ? ? ? ? ? ? ? ? ? $avatar_name = $utilService->create_qiniu_unqiue_name(2,$insertGetId,$path);
? ? ? ? ? ? ? ? ? ? if(!empty($avatar_name)){
? ? ? ? ? ? ? ? ? ? ? ? $QiniuServices = new Qiniu(config(‘config.bucket_key‘)[2],true);
? ? ? ? ? ? ? ? ? ? ? ? if(!empty($QiniuServices->upload($avatar_name, $path))){
? ? ? ? ? ? ? ? ? ? ? ? ? ? $userLogic->where(‘id‘,‘=‘,$insertGetId)->update([‘avatar‘=>$avatar_name,‘bucket_space‘=>config(‘config.bucket_key‘)[2]]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? //delete uploaded file from local
? ? ? ? ? ? ? ? ? ? ? ? ? ? $filesystem->delete($avatar_upload_path.$temp_name);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? log_records(‘新增普通用户:‘.$request->get(‘mobile‘));
? ? ? ? ? ? ? ? show_message(‘新增普通用户成功!‘, ‘/User/index‘, 1000,0);exit;
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? show_message(‘新增用户失败!‘,‘goback‘,1000,0);exit;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return view(‘backstage.user.add‘,$this->data);
? ? }
是不是很简单,动手操作下吧
?
原文:http://xialluyouyue.iteye.com/blog/2265956