ThinkPhp5 图片上传实例

ThinkPhp5 图片上传实例

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章添加</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<h3>文章添加</h3>
<form action="save" method="post" enctype="multipart/form-data">
文章标题:<input type="text" name="title" value=""><br/><br/>
文章描述:<input type="text" name="description" value=""><br/><br/>
文章封面:<input type="file" name="image_url" /> <br><br>
    <button type="submit">提交</button><br><br>
</form>

<img src="" class="img" width="300">

<script type="text/javascript">
    $("input[name='image_url']").change(function(){
        $(".img").attr("src",URL.createObjectURL($(this)[0].files[0]));
    });
</script>
</body>
</html>

样例会在选择图片后可在下方预览图片 ,效果如下: 

 

路由

Route::resource('article', 'article/index');

 控制器

<?php

namespace app\admin\controller;

use think\facade\Request;
//use think\Request;
use think\Controller;
use think\DB;

class Article extends Controller
{
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $file = request()->file('image_url');
        $info = $file->move( '../public/uploads/image');
        if($info){
            // 成功上传后 获取上传信息
            $_POST['image_url'] = '/uploads/image/'.$info->getSaveName();
            $row = DB::name('article')->insert($_POST);
            if($row){
                return "<script>alert('添加成功');window.location.href='index?cancel=yes';</script>";
            }
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }


    }

}

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值