分页与文件上传

原创 2018-12-03 15:31:46 242
摘要:分页查询数据步骤:一、先在数据库建立use表,添加相应字段,建表略;二、开发顺序尽量是先开发模型,故在model文件夹中,建立Use.phpmodel/Use.php代码如下:<?php  namespace app\index\model; use think\Model; class UserModel extends Mod

分页查询数据步骤:

一、先在数据库建立use表,添加相应字段,建表略;

二、开发顺序尽量是先开发模型,故在model文件夹中,建立Use.php

model/Use.php代码如下:

<?php 
namespace app\index\model;
use think\Model;

class UserModel extends Model
{
	// 指定默认数据表名
	protected $table = 'user';

	// 指定默认ID
	protected $pk = 'user_id';
}

三、控制器代码书写

<?php 
namespace app\index\controller;
use think\Controller;
use app\index\model\User as UserModel;//防止冲突
use think\facade\Request;

class User extends Controller
{
	//分页查询
	public function page()
	{
		//分页配置
		$config = [
			'type' => 'bootstrap',
			'var_page' => 'page',
			
		];

		//每页数量
		$num = 10;

		//是否是简单分页
		$simple = false;

		//获取所有分页数据:返回值是分页对象: think\Paginate
		$paginate = UserModel::paginate($num, $simple, $config);

		//渲染分页的HTML,返回分页变量
		$page = $paginate->render();

		//将分页对象赋值给模板
		$this->assign('users', $paginate);

		//将分页变量赋值给模板
		$this->assign('page', $page);

		//渲染模板
		return $this->fetch();

		//提示: tp51自带的分页功能很不灵活,更多时候,需要使用自己写的分页类

	}


	//文件上传
	//1.渲染文件上传页面
	public function upload()
	{
		return $this->fetch();
	}

	//2.处理文件上传
	public function uploadFile()
	{
		//1.获取上传的文件信息(Request请求对象中的file(),返回文件对象think/File)
		$file = Request::file('file');
		
		//2.将文件从临时目录移到到服务器上的指定目录
		if (is_null($file)) {
			$this->error('没有选择任何文件');
		} 
		
		$rule = ['size'=>2097152, 'ext'=>'jpg,jpeg,png,gif','type'=>'image/jpeg,image/png,image/gif'];
		if($file->check($rule)) {
			$fileInfo = $file->move('uploads');
			$res = '<h3 style="color:green;">上传成功</h3>文件名是:'.$fileInfo->getSaveName();		
		} else {
			$res = '<h3 style="color:red;">上传失败</h3>'.$file->getError();	
		}			
		return $res;
	}
}

四、view页面

控制器中,渲染多少页面,在对应的目录下就要有多少页面,此案例中,需要page.html和 upload.html,页面结构及包含的代码略


批改老师:天蓬老师批改时间:2018-12-03 16:00:59
老师总结:分页是信息展示的重要手段, 难以想像没有分页,众多数据应该如何展示,你可以动手 写个分页类,导入到项目中用用看. 文件 上传要分二步, 但为什么不一步到位上传到服务器,而是要先上传到本地临时目录,再上传到服务器上呢?

发布手记

热门词条