Thinkphp 文件上传

1、路由

Route::rule('fileUpload/:dir','index/FileUpload/index');

2、页面主要内容

 $('#exampleModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget)
            var imgpath = button.data('imgpath')
            var title = button.data('imgtitle')
            var info = button.data('productinfo')
            var productid = button.data('productid')


            if (productid === undefined) {
                window.alert("productid 未定义");
            }

            var modal = $(this)
            modal.find('.modal-title').text(title)
            //单图
            //modal.find('.modal-body img').attr('src',imgpath)                     
            modal.find('.modal-footer .info').text(info)

            //设置当前 productid
            modal.find('#productid').attr('value', productid)

            //设置上传表单productid
            modal.find('#productid').attr('value', productid)

            //清空元素
            modal.find('.carousel-indicators').empty()
            modal.find('.carousel-inner').empty()

            var productid = $('#productid').attr('value');
            var formData = new FormData();
            formData.append('productid', productid);
            formData.append('refresh', 1);

            $.ajax({
                type: 'post',
                cache: false,
                url: '/index.php/fileUpload/product',
                data: formData,
                processData: false,  // 不处理数据
                contentType: false,   // 不设置内容类型
                dataType: "json",
                success: function (data) {
                    if (data['status'] == 1) {
                        var modal = $('#exampleModal')
                        var images = data['images']// button.data('images')

                        var init = true;

                        //重新添加图片
                        for (var key in images) {
                            if (init) {
                                modal.find('.carousel-indicators').append("<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"" + key + "\" class=\"active\"></li>")
                                modal.find('.carousel-inner').append(" <div class=\"carousel-item active\"> <center><img class=\"ProductImages\" src=\"" + images[key]['file_path'] + "\"/></center> </div>")
                                init = false;
                            } else {
                                modal.find('.carousel-indicators').append("<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"" + key + "\"></li>")
                                modal.find('.carousel-inner').append(" <div class=\"carousel-item\"> <center><img class=\"ProductImages\" src=\"" + images[key]['file_path'] + "\"/></center> </div>")
                            }
                        }
                    } else {
                        alert("更新出错")
                    }
                },
                error: function (data) {
                    alert('更新出错');
                }
            })
        })

        $('#submit').on('click', function (event) {
            var formData = new FormData();
            formData.append('image', $('#file')[0].files[0]);
            formData.append('productid', $('#productid').attr('value'));
            formData.append('refresh', 0);
            $.ajax({
                type: 'post',
                cache: false,
                url: '/index.php/fileUpload/product',
                data: formData,
                processData: false,  // 不处理数据
                contentType: false,   // 不设置内容类型
                dataType: "json",
                success: function (data) {
                    if (data['status'] == 1) {
                        var modal = $('#exampleModal')
                        var images = data['images']// button.data('images')

                        //清空元素
                        modal.find('.carousel-indicators').empty()
                        modal.find('.carousel-inner').empty()

                        //重新添加图片
                        for (var key in images) {
                            //确保刚上传的文件被激活
                            if (key == (images.length - 1)) {
                                modal.find('.carousel-indicators').append("<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"" + key + "\" class=\"active\"></li>")
                                modal.find('.carousel-inner').append(" <div class=\"carousel-item active\"> <center><img class=\"ProductImages\" src=\"" + images[key]['file_path'] + "\"/></center> </div>")
                            } else {
                                modal.find('.carousel-indicators').append("<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"" + key + "\"></li>")
                                modal.find('.carousel-inner').append(" <div class=\"carousel-item\"> <center><img class=\"ProductImages\" src=\"" + images[key]['file_path'] + "\"/></center> </div>")
                            }
                        }

                        // alert('上传完成!')
                    } else {
                        alert('上传错误')
                    }
                },
                error: function (data) {
                    alert('上传错误');
                }
            })
        })
    })
//...
    <div class="ProductPreview">
        {notempty name='$product.qrcode.file_path')}
        <img src="{$product.qrcode.file_path}" data-toggle="modal" data-target="#exampleModal" data-imgpath="{$product.qrcode.file_path}"
            data-imgtitle="{$product.name}" data-productinfo="{$product.type.name} / {$product.model}" data-images="{$product.images}"
            data-productid="{$product.id}">
        </a>
        {else/}
        <img data-toggle="modal" data-target="#exampleModal" data-imgpath="{$product.qrcode.file_path}" data-imgtitle="{$product.name}"
            data-productinfo="{$product.type.name} / {$product.model}" data-images="{$product.images}" data-productid="{$product.id}">
        </a>
        {/notempty}
    </div>
//...
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- 单图 -->
                <!--
                    <center><img src="" style="width:auto;height:auto;max-height:300px;max-width:100%;" /></center>
                -->

                <!-- 多图 -->

                <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
                    <ol class="carousel-indicators">
                        <!--
                        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
                        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                        -->
                    </ol>
                    <div class="carousel-inner">
                        <!-- 原案例 -->
                        <!--
                          <div class="carousel-item active">
                            <img class="d-block w-100" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_164b27b1eb7%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_164b27b1eb7%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.921875%22%20y%3D%22217.7%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" alt="First slide">
                          </div>
                          <div class="carousel-item">
                            <img class="d-block w-100" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_164b27b1eb7%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_164b27b1eb7%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.921875%22%20y%3D%22217.7%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" alt="Second slide">
                          </div>
                          <div class="carousel-item">
                            <img class="d-block w-100" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_164b27b1eb7%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_164b27b1eb7%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.921875%22%20y%3D%22217.7%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" alt="Third slide">
                          </div>
                          -->
                    </div>
                    <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
                        <span class="PrevIcon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                    </a>
                    <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
                        <span class="NextIcon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                    </a>
                </div>
                <center>

                    <form id="uploadForm" enctype="multipart/form-data">
                        <div class="input-group">
                            <input type="file" name="image" class="form-control" id="file" />
                            <div class="input-group-prepend">
                                <div class="input-group-text" id="btnGroupAddon">
                                    <input type="button" value="上传" id="submit" />
                                    <input type="hidden" name="productid" id="productid" value="" />
                                </div>
                            </div>

                        </div>

                        <br>

                    </form>

                </center>
            </div>

            <div class="modal-footer">

                <h6 class="info">info</h6>
            </div>
        </div>
    </div>
</div>

3、后台

<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\File;

use app\index\model\ProductModel;
use app\index\model\ExtraProductModel;

class FileUploadController extends Controller
{
    public function index($dir){        
        $id=request()->param('productid');
        $refresh=request()->param('refresh');

        $result;
      
        if($refresh==1){
            $product=ProductModel::where('id', $id)->find();
            $images=$product->images;
            
            $result['status']=1;
            $result['images']=$images;       
        }else{
            $file =request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
             if($file){
            $info = $file->move(UPLOAD_PATH.$dir);
            if($info){               
                $extraProduct =new ExtraProductModel();
                $extraProduct->name=$info->getFilename();
                $extraProduct->file_path='/upload/'.$dir.'/'.$info->getSaveName();
                $extraProduct->product_id=$id;
                $extraProduct->save();
               
                $product=ProductModel::where('id', $id)->find();
                $images=$product->images;
                
                $result['status']=1;
                $result['images']=$images;                
            }else{
                $result['status']=0;
            }
        }else{
            $result['status']=0;
        }
    }
        return $result;
    }
}

 

php 树形列表

TreeView.php

<?php
class TreeView {
    public $childName = "child";
    public $parentid;
    public $id;
    public $nameColumn;
    function __construct($parentid, $id,$nameColumn) {
        $this->parentid = $parentid;
        $this->id = $id;
        $this->nameColumn=$nameColumn;
    }
    
    public function display($Nodes) {
        echo '<div class="TreeView"><ul>';
        $GroupNodes = $this->buildTree($Nodes->list, $this->parentid, $this->id);
        $this->showTree($GroupNodes);
        echo '</ul>';
    }

    function buildTree($temp, $parentid, $idKey) {
        $grouped = $this->reGroup($temp, $parentid, $idKey);
        $fnBuilder = function ($siblings) use(&$fnBuilder, $grouped, $idKey) {
            foreach ($siblings as $k => $sibling) {
                $id = $sibling[$idKey];
                if (isset($grouped[$id])) {
                    $sibling[$this->childName] = $fnBuilder($grouped[$id]);
                }
                $siblings[$k] = $sibling;
            }
            return $siblings;
        };
        $tree = $fnBuilder($grouped[0]);
        return $tree;
    }


    function showTree($grouped) {
       foreach($grouped as $subGroupKey=>$subGroup){
           if(is_array($subGroup)){              
               if($subGroupKey===$this->childName){
                   //当前有子集
                   echo '<ul>';
                   $this->showTree($subGroup);
                   echo '</ul></li>';
               }else{
                   echo '</li>';
                   $this->showTree($subGroup);
               }
           }else{
               if($subGroupKey===$this->nameColumn){
                   echo '<li><div class="clickOnCollpose"><div class="title"><a>'.$subGroup.'</a></div></div>';
               }
           }
       }
    }
   
    function reGroup($temp, $parentid, $id) {
        $group = array();
        foreach ($temp as $item) {
            $key = $item[$parentid];
            $group[$key][] = $item;
        }
        return $group;
    }
    
}
class Nodes{
    public $list;

    function __construct(){
        $this->list=array();
    }

    public function add($Node) {
        array_push($this->list, $Node);
    }
    public function removeByNode($Node) {
        for ($i = 0;$i < count($this->list);$i++) {
            if ($this->list[$i] === $Node) {
                $this->remove($i);
            }
        }
    }
    public function removeByIndex($startIndex, $length = 0) {
        array_splice($this->list, $startIndex, $lenght);
    }
    public function clear() {
        unset($this->list);        
    }    
}

?>

TreeView.css

ul{
    list-style:none;
    padding-left: 1em;
}
.clickOnCollpose{
    display: inline-block;
    background-color: #eee;
    width:100%;
    margin:4px 0px 4px 0px;
    border-radius: 6px;
    border-width: 1px;
    border-color: #aaa;
    border-style: solid;
    padding:4px;
}

.clickOnCollpose:hover{
    background-color: #337ABC;
    color:#FFFFFF;
    padding:4px;
    border-color:#FFF;
}

.title{
    float:left;
    text-indent: 10px;
}
.count-near{
    background-color:#FF0000;
    border-radius:20px;
    color:#FFF;
    font-weight:bold;
    width:20px;
    height:20px;
    text-align:center;
    float:left;
    margin-left:20px;
}
.count-far{
    background-color:#FF0000;
    border-radius:20px;
    color:#FFF;
    font-weight:bold;
    width:20px;
    height:20px;
    text-align:center;
    float:right;
}


li{
    cursor:hand;
}
.treeview{
   width:100%;
}

TreeView.js

$(document).ready(function(){
    //默认从第2级隐藏
    $(".treeView ul li").find("ul").toggle();
 
    $(".clickOnCollpose").on('click',function(){    
        //展开/收缩下级
        $(this).parent().find("ul").toggle();  
 
        //展开/收缩下下级
        $(this).parent().find("ul li ul").toggle();        
    })
 
    $(".clickOnCollpose").mouseenter(function(){
        var count=$(this).next().children().length;
        //if(count>0){
            //class修改成 count-near 更改样式
            $(this).append("<div class='count-far'> "+count+" </div>");       
        //}
    })
 
    $(".clickOnCollpose").mouseleave(function(){     
        //class修改成 count-near 更改样式
         $(this).find(".count-far").remove();
    })
 
})

==============================================================

Demo.php

<?php
require_once("TreeView.php");
?>

<html>
<head>
<title>测试</title>
<link rel="stylesheet" href="./TreeView.css" type="text/css"/>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script src="./TreeView.js"></script>
</head>
<body>

<?php

$n=new Nodes();
$n->add( ["id" => 1, "name" => "name0-1", "parentid" => 0]);
$n->add( ["id" => 2, "name" => "name1-2", "parentid" => 1]);
$n->add( ["id" => 3, "name" => "name1-3", "parentid" => 1]);
$n->add( ["id" => 4, "name" => "name2-4", "parentid" => 2]);
$n->add( ["id" => 5, "name" => "name2-5", "parentid" => 2]);
$n->add( ["id" => 6, "name" => "name4-6", "parentid" => 4]);
$n->add( ["id" => 7, "name" => "name1-7", "parentid" => 1]);
$n->add( ["id" => 8, "name" => "name2-8", "parentid" => 2]);
$n->add( ["id" => 9, "name" => "name2-9", "parentid" => 2]);
$n->add( ["id" => 10, "name" => "name2-10", "parentid" => 2]);
$n->add( ["id" => 11, "name" => "name8-11", "parentid" => 8]);
$n->add( ["id" => 12, "name" => "name8-12", "parentid" => 8]);
$n->add( ["id" => 13, "name" => "name11-13", "parentid" => 11]);
$n->add( ["id" => 14, "name" => "name0-14", "parentid" => 0]);
$n->add( ["id" => 15, "name" => "name0-15", "parentid" => 0]);


$treeview=new TreeView("parentid","id","name");
//可写作$treeview=new TreeView(2,0,1);
$treeview->display($n);
?>
</body>
</html>