上传到本地参考:https://www.jb51.net/article/119950.htm#comments
上传到七牛云:
环境
- composer
https://docs.phpcomposer.com/00-intro.html - thinkphp5
https://www.cnblogs.com/wangliancomcn/p/10283603.html - 七牛云sdk
https://developer.qiniu.com/kodo/sdk/1241/php
项目结构
html 页面
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h2>文件上传</h2>
<FORM method="post" enctype="multipart/form-data" class="form" action="{:url('upload')}">选择文件:
<INPUT type="file" class="files" name="files"><br/>
<INPUT type="submit" class="btn" value=" 提交 ">
</FORM>
</body>
</html>
Index (controller)
<?php
namespace app\index\controller;
use think\Controller;
use app\common\lib\Upload;
use think\Request;
class Index extends Controller
{
public function index()
{
return $this->fetch();
}
//上传到七牛云
public function upload(){
$image = Upload::image();
if($image){
$data = [
'status' =>1,
'message' => 'OK',
'data' => config('qiniu.image_url').'/'.$image,
];
echo json_encode($data);exit;
}else{
echo json_encode(['status' =>0,'message' => '上传失败']);
}
}
}
Upload (controller)
<?php
namespace app\common\lib;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Upload{
public static function image(){
if(empty($_FILES['files']['tmp_name'])){
exception("图片error",404);
}
//要上传的文件
$file = $_FILES['files']['tmp_name'];
$ext = explode('.',$_FILES['files']['name']);
$ext = $ext[1];
//构建鉴权对象
$auth = new Auth(config('qiniu.ak'),config('qiniu.sk'));
//生成token
$token = $auth->uploadToken(config('qiniu.bucket'));
//上传到七牛云后保存的文件名
$key = date('Y')."/".date('m')."/".substr(md5($file),0,5).date('YmdHis')
.rand(0,9999).'.'.$ext;
$uploadMgr = new UploadManager();
list($res,$err) = $uploadMgr->putFile($token,$key,$file);
if($err != null){
return null;
}else{
return $key;
}
}
}
Qiniu.php
<?php
return [
'ak' => '改成自己的ak',
'sk' => '改成自己的sk',
'bucket' => '改成自己的',
'image_url' => '改成自己的',
];
思路:当用户在index/index.html中选择好图片,点击提交时,会去调用index(controller)的upload方法。upload方法 调用/common/lib/Upload的image方法。判断文件是否为空,空报错。获取file文件的名称,其中files和html中的file name必须一样。Upload必须引入use Qiniu\Auth;use Qiniu\Storage\UploadManager;
还有uploadify 免费版的下架了 而且一直运行不成功 等一个有缘人讨论下!!http://www.uploadify.com/demos/