TP5上传图片到本地

0 篇文章 0 订阅

TP5上传图片到本地

这个图片上传代码加上了数据库操作
注释写的基本新手都会理解的

  • PHP代码
<?php
namespace app\index\controller;
use think\Controller;
use think\Validate;
use think\Db;

class Index extends Controller
{
    public function index()
    {
       $photo=Db::table('image');//连接数据库
       $D=$photo->where('id',1)->find();
       
        
        
        return $this->fetch('index');
    }
    public function picture()
    {

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        //校验器,判断图片格式是否正确  //validate 验证函数  //这验证是否是图片,定义验证的方法  
        //['image' => $file]是tp5自己带的图片验证
        //['image'=> 'max:2097152']文件限制大小2m max换size也行
         if (true !== $this->validate(['image' => $file], ['image' => 'require|image'],['image'=> 'max:2097152'])) {
            $this->error('请选择图像文件或者文件大小大于2m');
        } else {
            // 移动到框架应用根目录/public/uploads/   
            //ROOT_PATH项目根目录
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // 成功上传后 获取上传信息

                //存入相对路径/upload/日期/文件名
                 //getSaveName是输出文件的位置以及文件名。系统会自动穿件以时间为名的文件夹,然后输出文件夹的名字和图片的名字。
                $data = DS . 'uploads' . DS . $info->getSaveName();
                //添加到数据库
                //data是快递添加
                $add=Db::table('image')
                   ->data(['photo'=>$data])
                   ->insert();
                 $this->success('新增成功'); 
                //模板变量赋值
                $this->assign('image', $data);
                return $this->fetch('index');


            } else {
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }

}
  • 模板代码
<!DOCTYPE html>
<html>
<head>
	<title>1234</title>
	<link rel="stylesheet" type="text/css" href="__ROOT__/index/css/index.css">
	
</head>
<body>
	<form method="post" enctype="multipart/form-data" class="form" action="{:url('picture')}">
    选择图像文件:<input type="file" class="file" name="image"><br/>
    <input type="submit" class="btn" value=" 提交 ">
</form>


</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值