`

laravel 七牛云如何处理上传文件

阅读更多

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代码进行验证了。

config中上传头像配置:

//上传头像文件的配置选项

    'avatar' =>[

        'size' => '2048000',

        'extension' =>[

            0             =>'jpg',

            1             =>'jpeg',

            2             =>'bmp',

            3             =>'gif',

            4             =>'png'

        ] 

    ],

'bucket_key'        =>  [

        1               => 'id-images', //身份证

        2               => 'avator-images', //头像

        3               => 'drugstore-images', //药店营业执照

        4               => 'product-images', //产品图片

        5               => 'article-images', //文章图片

        6               => 'topic-images', //话题图片章

        7               => 'ue-images', //ueditor上传图片

        8               => 'slide-images', //幻灯片

        9               => 'test-paper-images', //题卷图片

        10              => 'event-images', //活动图片

        11              => 'audio', //音频

        12              => 'video',// 视频

        13              => 'group-images',// 群组头像

    ],

php代码:

控制器代码:

namespace App\Http\Controllers\Backstage\User;

use Illuminate\Http\Request;

use Services\Qiniu;

use Illuminate\Filesystem\Filesystem;

use Illuminate\Support\Facades\DB;

class UserController extends \App\Http\Controllers\Backstage\Controller {

.......

public function add(Request $request){

        //实例化User模型对象,继承\Illuminate\Database\Eloquent\Model

        $userLogic = new \App\Logics\UserLogic();

        //判断是否是表单提交,所以在我们配置路由时候,路由的http请求方式不仅仅是get,而且也是post,参考        

         //laravel如何配置路由

        if($request->isMethod('post')){ 

            $temp_name = '';

            $avatar_upload_path = '';

            $path = "";

            //判断表单提交是否含有文件操作

            if($request->hasFile('avatar')){ 

                //获取上传文件信息,返回结果集是一个对象,该对象可以获取到缓存在tmp文件夹中的文件                  

                   //名、上传文件的后缀、缓存在tmp文件夹下的文件的绝对路径、文件大小等等

                $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;

                }

                //laraval 第三方扩展类库Filesystem,很强大,自行查询,laravel api文档

                //https://laravel.com/api/5.0/Illuminate/Filesystem/Filesystem.html

                $filesystem = new Filesystem();

                //定义laravel项目中上传路径

                $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自定义的方法,就不写了

                show_message('新增普通用户成功!', '/User/index', 1000,0);exit;

            }else{

                show_message('新增用户失败!','goback',1000,0);exit;

            }

        }

        return view('backstage.user.add',$this->data);

    }

.......

}

4,Logic文件夹中定义的部分代码如下:

<?php

namespace App\Logics;

use Illuminate\Support\Facades\DB;

/**

 * Description of UserLogic

 *

 * @author timlu

 */

class UserLogic extends \Illuminate\Database\Eloquent\Model{

    

    protected $table = "user";

    //put your code here

    public function getList($data = []){

        if (!empty($data['sortby']) && !empty($data['sortvalue'])) {

            $sortby = $this->table.'.'.$data['sortby'];

            $sortvalue = trim($data['sortvalue']);

        } else {

            $sortby = $this->table.'.id';

            $sortvalue = 'desc';

        }

        $list = DB::table($this->table)

            ->where(function($query) use($data) {

                if (!empty($data['mobile'])) {

                    $query->where($this->table . '.mobile', 'like', '%' . $data['mobile'] . '%');

                }

            })->where(function($query) use($data) {

                if (!empty($data['phone'])) {

                    $query->where($this->table . '.phone', 'like', '%' . $data['phone'] . '%');

                }

            })->where(function($query) use($data) {

                if (!empty($data['realname'])) {

                    $query->where($this->table . '.realname', 'like', '%' . $data['realname'] . '%');

                }

            })->where(function($query) use($data) {

                if (!empty($data['nickname'])) {

                    $query->where($this->table . '.nickname', 'like', '%' . $data['nickname'] . '%');

                }

            })->where(function($query) use($data) {

                if (!empty($data['start_time']) && !empty($data['end_time'])) {

                    $query->where($this->table . '.lastlogin', '>=', $data['start_time'])

                    ->where($this->table . '.lastlogin', '<=', $data['end_time']);

                } else if (!empty($data['start_time'])) {

                    $query->where($this->table . '.lastlogin', '>=', $data['start_time']);

                } else if (!empty($data['end_time'])) {

                    $query->where($this->table . '.lastlogin', '<=', $data['end_time']);

                }

            })

            ->select('id','realname','nickname','mobile','score','phone','lastlogin','is_active')

            ->orderBy($sortby, $sortvalue)

            ->take($data['pageSize'])

            ->skip($data['pageNo'] > 1 ? ($data['pageNo'] - 1) * $data['pageSize'] : 0)

            ->get();

        $count = 0;

        if (!empty($list)) {

            $count = DB::table($this->table)

                ->where(function($query) use($data) {

                    if (!empty($data['mobile'])) {

                        $query->where($this->table . '.mobile', 'like', '%' . $data['mobile'] . '%');

                    }

                })->where(function($query) use($data) {

                    if (!empty($data['phone'])) {

                        $query->where($this->table . '.phone', 'like', '%' . $data['phone'] . '%');

                    }

                })->where(function($query) use($data) {

                    if (!empty($data['realname'])) {

                        $query->where($this->table . '.realname', 'like', '%' . $data['realname'] . '%');

                    }

                })->where(function($query) use($data) {

                    if (!empty($data['nickname'])) {

                        $query->where($this->table . '.nickname', 'like', '%' . $data['nickname'] . '%');

                    }

                })->where(function($query) use($data) {

                    if (!empty($data['start_time']) && !empty($data['end_time'])) {

                        $query->where($this->table . '.lastlogin', '>=', $data['start_time'])

                        ->where($this->table . '.lastlogin', '<=', $data['end_time']);

                    } else if (!empty($data['start_time'])) {

                        $query->where($this->table . '.lastlogin', '>=', $data['start_time']);

                    } else if (!empty($data['end_time'])) {

                        $query->where($this->table . '.lastlogin', '<=', $data['end_time']);

                    }

                })->count();

        }

        return [$list, $count];

    }

    

    public function getUserInfoById($id){

        return self::find($id);

    }

    

    public function insertUser(\Illuminate\Http\Request $request){

        if(!empty($request->get('realname',''))){

            $data['realname']= strval($request->get('realname',''));

        }   

        $data['nickname']= strval($request->get('nickname',''));

        $data['mobile']=strval($request->get('mobile',''));

        if(!empty($request->get('passwd',''))){

            $data['passwd']=md5(strval($request->get('passwd','')));

        }

        $data['score'] = intval($request->get('score',0));

        $data['sex'] = strval($request->get('sex',1));

        $data['birthday']=strval($request->get('birthday',''));

        $data['email']=strval($request->get('email',''));

        if(!empty($request->get('qq',''))){

            $data['qq']=strval($request->get('qq',''));

        }

        if(!empty($request->get('ip',''))){

            $data['ip']=strval($request->get('ip',''));

        }

        $data['phone']=strval($request->get('phone',''));

        $data['age']=intval($request->get('age',0));

        $data['is_active']=strval($request->get('is_active',0));

        return DB::table($this->table)->insertGetId($data);

    }

    

    public function updateUser(\Illuminate\Http\Request $request){

        if(!empty($request->get('realname',''))){

            $data['realname']= strval($request->get('realname',''));

        }   

        $data['nickname']= strval($request->get('nickname',''));

        $data['mobile']=strval($request->get('mobile',''));

        if(!empty($request->get('passwd',''))){

            $data['passwd']=md5(strval($request->get('passwd','')));

        }

        $data['score'] = intval($request->get('score',0));

        $data['sex'] = strval($request->get('sex',1));

        $data['birthday']=strval($request->get('birthday',''));

        $data['email']=strval($request->get('email',''));

        if(!empty($request->get('qq',''))){

            $data['qq']=strval($request->get('qq',''));

        }

        if(!empty($request->get('ip',''))){

            $data['ip']=strval($request->get('ip',''));

        }

        $data['phone']=strval($request->get('phone',''));

        $data['age']=intval($request->get('age',0));

        return DB::table($this->table)->where('id','=',intval($request->get('id')))->update($data);

    }

}

 

是不是很简单,动手操作下吧

 

2
2
分享到:
评论

相关推荐

    七牛云上传图片、拉取数据、分片上传

    七牛云上传图片、拉取数据代码,下载七牛sdk修改配置即可使用,使用的ci框架

    Laravel中前端js上传图片到七牛云的示例代码

    以下Laravel中使用浏览器端上传图片到七牛云,下面只是做一些简单的流程实例。 1. 首先引入相应的js文件,下面是通过CDN引入的StaticfileCDN,当然也有其他很多方式下载, bower,git,官网的SDK 七牛js基于...

    laravel-ueditor:laravel5的UEditor包

    支持本地和七牛云存储(在配置文件中配置),默认为本地上传 public/uploads 修改日志 增加配置文件配置说明及七牛云存储使用说明 v1.1.0 增加了测试视图文件,修改了head视图错误路径 v1.0.1 修改了其中路径错误,将...

    laravel诗词博客-匠心编程,热爱生活。喜欢就Star吧

    支持七牛云对象存储文件上传 可能是世界上最漂亮的博客之一 服务器要求 安装Nginx / Apache 安装MySQL 安装PHP&gt; = 7.1.3【推荐版本7.2】 PHP必要扩展 DOM PHP 扩展 OpenSSL PHP 拓展 PDO PHP 拓展 Mbstring ...

    企业内容建站系统 ModStartCMS v7.9.0 内容推荐支持,用户授权升级

    大文件分片上传,进度条显示,已上传文件管理 强大的模块扩展功能,所有模块可以无缝集成,支持在线安装、卸载模块 完善的开发助手,实现模块、主题的的一键创建 完善的后台权限管理,支持基于RBAC的权限管理系统...

    现代化个人博客系统 ModStartBlog v5.6.0 备案信息完善,功能组件优化

    大文件分片上传,进度条显示,已上传文件管理 强大的模块扩展功能,所有模块可以无缝集成,支持在线安装、卸载模块 完善的开发助手,实现模块、主题的的一键创建 完善的后台权限管理,支持基于RBAC的权限管理系统...

    现代化个人博客系统 ModStartBlog v5.4.0 登录界面改版,新增联系方式

    大文件分片上传,进度条显示,已上传文件管理 强大的模块扩展功能,所有模块可以无缝集成,支持在线安装、卸载模块 完善的开发助手,实现模块、主题的的一键创建 完善的后台权限管理,支持基于RBAC的权限管理系统...

    现代化个人博客系统 ModStartBlog v5.7.0 简约纯白主题,富文本大升级

    大文件分片上传,进度条显示,已上传文件管理 强大的模块扩展功能,所有模块可以无缝集成,支持在线安装、卸载模块 完善的开发助手,实现模块、主题的的一键创建 完善的后台权限管理,支持基于RBAC的权限管理系统...

    laravel-u-editor:laravel5的UEditor。 支持i18n。 UEditor是来自百度的Rich Text Web编辑器

    支持本地和七牛云存储,默认为本地上传 public/uploads ChangeLog v1.4.5 增加laravel的storage的支持 增加阿里云存储的支持 增加Lumen5的provider支持 v1.4.3 (bug已删除) 1.4.0 版 支持 laravel5.3 更新百度 ...

    ModStartBlog 稳定版

    大文件分片上传,进度条显示,已上传文件管理 强大的模块扩展功能,所有模块可以无缝集成,支持在线安装、卸载模块 完善的开发助手,实现模块、主题的的一键创建 完善的后台权限管理,支持基于RBAC的权限管理系统...

    zhihu-app:laravel-vue-zhihu

    头像上传至七牛云存储 修改密码 忘记密码(邮件认证) 用户相互关注(邮件提醒) 用户发送私信(消息通知) 显示私信(已读和未读) 标志私信 标志私信全部已读 回复私信 个人主页(特定数据) 问题 问题列表 收藏...

    博客

    Laravel诗词博客-匠心编程,热爱生活。 感谢各位朋友的支持,很开心和你分享我的代码,希望大家...支持七牛云对象存储文件上传 可能是世界上最漂亮的博客之一 服务器要求 安装Nginx / Apache 安装MySQL 安装PHP&gt; = 7.1.

Global site tag (gtag.js) - Google Analytics