laravel上传文件到七牛云存储

背景

最近在用PHP和laravel框架作一个图片网站,须要将图片存贮到云端,搜索下了对比了下功能,发现七牛云存储不错(主要小流量免费),便选择使用七牛做为图片存储空间。
要实现的功能很简单,选择本地图片上传到七牛,上传成功后添加图片及上传者信息到数据库。本文主要讲php经过七牛php-sdk显现简单的图片上传。

准备

一、已存在php5.4,laravel5,mysql5.5(没有使用到),composer,七牛帐号(注册[传送门](https://portal.qiniu.com/signup))
二、安装php-sdk,采用composer安装,打开laravel根目录下的composer.json,添加"qiniu/php-sdk": "~7.0"到require关键字下,保存,运行composer update安装,即完成php-sdk的安装。![composer配置](http://img.blog.csdn.net/20150413194853209)
三、在config目录下添加qiniu.php配置文件,配置七牛相关的信息,配置以下
<?php
    /** * 七牛上传配置 */ return [ 'accessKey'=>'yourAccesskey', 'secretKey'=>'yourSecretkey', 'bucket'=>'fpstatic',//上传空间名称 'domain'=>'http://7xidgf.com1.z0.glb.clouddn.com' ];//空间域名
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
四、添加UploadController 控制器,并在router.php文件中添加一条路由,以下
`Route::controller('upload','UploadController');`

代码实现

先贴整个控制器代码
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use PhpParser\Node\Expr\Variable; use Illuminate\Support\Facades\Redis; use Illuminate\Support\Facades\Input; //导入七牛相关类 use Qiniu\Auth; use Qiniu\Storage\BucketManager; use Qiniu\Storage\UploadManager; class UploadController extends Controller { public function __construct(){ $this->middleware('activeUsers'); } public function getIndex() { var_dump(isset($ret)); $data=$this->getPageData();//获取页面显示所需数据 $data['uploadSelected']=true; return view('portal/upload')->with('data',$data); } /** * 获取页面显示所需数据 * @return multitype:boolean \Illuminate\Support\Facades\mixed NULL */ private function getPageData(){ $data=[];//返回视图数据 $data['loginCount']=Redis::get('loginNum');//登录人数 $data['activeUsersCount']=Input::get('activeUsers');//活跃人数 return $data; } public function postDoupload(){ $token=$this->getToken(); $uploadManager=new UploadManager(); $name=$_FILES['file']['name']; $filePath=$_FILES['file']['tmp_name']; $type=$_FILES['file']['type']; list($ret,$err)=$uploadManager->putFile($token,$name,$filePath,null,$type,false); if($err){//上传失败 var_dump($err); return redirect()->back()->with('err',$err);//返回错误信息到上传页面 }else{//成功 //添加信息到数据库 return redirect()->back()->with('key',$ret['key']);//返回结果到上传页面 } } /** * 生成上传凭证 * @return string */ private function getToken(){ $accessKey=config('qiniu.accessKey'); $secretKey=config('qiniu.secretKey'); $auth=new Auth($accessKey, $secretKey); $bucket=config('qiniu.bucket');//上传空间名称 //设置put policy的其余参数 //$opts=['callbackUrl'=>'http://www.callback.com/','callbackBody'=>'name=$(fname)&hash=$(etag)','returnUrl'=>"http://www.baidu.com"]; return $auth->uploadToken($bucket);//生成token } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

视图代码javascript

@extends('common/index')

@section('content')
    <div class="row clearfix"> <div class="col-md-4 column"> </div> <div class="col-md-4 column"> <form name="form" role="form" method="post" action="{{url('/upload/doupload')}}" enctype="multipart/form-data" onsubmit="return isValidateFile('file');"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <label for="exampleInputFile">选择文件</label><input type="file" name='file' /> <p class="help-block"> </p> </div> <button type="submit" class="btn btn-default">上传</button> </form> </div> <div class="col-md-4 column"> @if (session('key')) <img alt="140x140" src="<?php echo config('qiniu.domain').'/'.session('key')?>?imageView2/2/w/400/h/400" class="img-rounded" /> @endif </div> </div> <script> function isValidateFile(obj) { var extend = document.form.file.value.substring(document.form.file.value.lastIndexOf(".") + 1); if (extend == "") { alert("请选择图片!"); return false; } else { if (!(extend == "jpg" || extend == "png" || extend =="gif")) { alert("请上传后缀名为jpg、png或gif的文件!"); return false; } } return true; } </script> @endsection 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

详解:

一、流程:
    上传页面选择图片,点击提交,提交到/upload/doupload,路由解析到uploadController下的postDoupload(不懂查看laravel手册路由章节,不用laravel就无所谓了,提交到对控制器器方法便可)
2上传流程
![上传流程](http://img.blog.csdn.net/20150413204935125)
so咱们首先要生成uptoken
三、导入七牛sdk相关的类
use Qiniu\Auth; use Qiniu\Storage\BucketManager; use Qiniu\Storage\UploadManager;
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
读取配置文件中的key,生成token方法
    /** * 生成上传凭证 * @return string */ private function getToken(){ $accessKey=config('qiniu.accessKey'); $secretKey=config('qiniu.secretKey'); $auth=new Auth($accessKey, $secretKey); $bucket=config('qiniu.bucket');//上传空间名称 //设置put policy的其余参数 //$opts=['callbackUrl'=>'http://www.callback.com/','callbackBody'=>'name=$(fname)&hash=$(etag)','returnUrl'=>"http://www.baidu.com"]; return $auth->uploadToken($bucket);//生成token }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

而后就要上传文件了,文件post到了这个方法php

public function postDoupload(){ $token=$this->getToken(); $uploadManager=new UploadManager(); $name=$_FILES['file']['name']; $filePath=$_FILES['file']['tmp_name']; $type=$_FILES['file']['type']; list($ret,$err)=$uploadManager->putFile($token,$name,$filePath,null,$type,false); if($err){//上传失败 var_dump($err); return redirect()->back()->with('err',$err);//返回错误信息到上传页面 }else{//成功 //添加信息到数据库 return redirect()->back()->with('key',$ret['key']);//返回结果到上传页面 } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

这里关键的一点是
$uploadManager->putFile($token,$name,$filePath,null,$type,false);
官方文档是这样的
list($ret, $err) = $uploadMgr->putFile($token, null, __file__);
坑爹的一点是抓狂,__file__不讲清楚,那只好去查他的源码了,
查看后获得,putFile方法参数依次为token,存储的文件名,真是路径,参数,和文件类型,传入相应的参数便可成功完成上传
4,在文件上传页面,点击提交以前检测文件是否为图片格式,这里参考的是一位网友的js判断html

<script> function isValidateFile(obj) { var extend = document.form.file.value.substring(document.form.file.value.lastIndexOf(".") + 1); if (extend == "") { alert("请选择图片!"); return false; } else { if (!(extend == "jpg" || extend == "png" || extend =="gif")) { alert("请上传后缀名为jpg、png或gif的文件!"); return false; } } return true; } </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

要注意的是记得给html页面中form的name属性设置为“form”java

五、上传成功后,将上传的图片显示在上传页面(固然也能够是其余页面,仅测试),直接使用上传成功后返回的key(即文件名)以及空间域名来生成完整的地址(固然不建议这样)mysql

总结

这仅仅是一个简单的例子,实现上传到七牛云存储的方法还有不少种(好比直接利用表单上传),具体可搜索【php 七牛】关键字。同时利用七牛也能进行功能丰富的图片处理,可查看七牛文档。
 [代码地址](https://github.com/kpmving/FP "optional title")
相关文章
相关标签/搜索