1. 程式人生 > >tp5簡單的多圖片上傳並預覽demo

tp5簡單的多圖片上傳並預覽demo

今天沒事去研究了一下多圖片同時上傳,看了很多案例,也下載了一些外掛,感覺都很複雜,就自己想了一個思路,做了個簡單的demo,程式碼貼出來,供大家參考一下。由於我也是小菜鳥,所以程式碼裡有什麼問題歡迎大家提出來。

這個多圖上傳的思路是:先新增一個<input type="file">的檔案按鈕,設定樣式opacity=0;z-index=1;覆蓋在一個普通按鈕<input type="button">上(新手注意哈,這裡z-index要設定pozition才有效,這裡要將file按鈕覆蓋到普通按鈕上,本就要設定pozition=absolute絕對定位);在選擇圖片後,生成預覽圖,同時新增<input type="file">,設定z-index=2,覆蓋到之前的file按鈕上,以此類推。

引入檔案:

    <link rel="stylesheet" type="text/css" href="/public/html/style/bootstrap.min.css">
    <script src="/public/html/js/jquery-3.1.0.min.js"></script>
    <script src="/public/html/js/bootstrap.min.js"></script>

HTML程式碼:

<form  method="post" enctype="multipart/form-data" action="{:url('index/fileupload/doUpload')}"  id="box">


    <!--file包裹-->
    <div class="addbtn_wrap">
        <input type="button" class="btn btn-primary addbtn" value="點選新增圖片">
        <input type="file" name="image[]" id="file1" style="z-index: 1" onchange="getPhoto(this)">
    </div>


    <!--圖片包裹-->
    <div class="img_wrap">

    </div>

    <input type="submit" value="開始上傳" class=" btn btn-primary ">


</form>

CSS樣式:

 <style>

        /*表單標籤*/
        #box{
            margin:50px auto;
            width:600px;
            padding-bottom: 10px;
            min-height:400px;
            background:#FF9;
        }

        /*點選新增圖片按鈕div包裹*/
        .addbtn_wrap{
            position: relative;
        }

        /*新增圖片按鈕*/
        .addbtn{
            position: absolute;
        }
        input[type=file]{
            width: 100px;
            position: absolute;
            top: 5px;
            opacity: 0;
        }

        /*提交按鈕*/
        input[type=submit]{
            margin: 0 auto;
            display: none;
        }

        /*所有圖片div包裹*/
        .img_wrap{
            width:600px;
            margin-top: 40px;
            float: left;
            margin-bottom: 40px;
        }


        .pic_wrap{
            width: 180px;
            height: 160px;
            float: left;
            position: relative;
            margin: 5px;
        }


        .img{
            width: 180px;
            height: 160px;
           float: left;
        }

        .delete{
            width: 180px;
            height: 160px;
            position: absolute;
            display: none;
            border-radius: 6px;
        }

        .delete img{
            float: right;
        }

    </style>

jquery程式碼:

<script type="text/javascript">


    /*預覽*/
    var count=1;
    function getPhoto(node) {

        var imgURL = "";
        try{
            var file = null;
            if(node.files && node.files[0] ){
                file = node.files[0];
            }else if(node.files && node.files.item(0)) {
                file = node.files.item(0);
            }

            try{
                imgURL =  file.getAsDataURL();
            }catch(e){
                imgRUL = window.URL.createObjectURL(file);
            }
        }catch(e){
            if (node.files && node.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    imgURL = e.target.result;
                };
                reader.readAsDataURL(node.files[0]);
            }
        }

        /*動態新增file和對應的圖片預覽*/
        createPic();
        createFile();

        count++;
        return imgURL;
    }

    /*建立圖片預覽元素*/
    function createPic() {
        var picText='<div class="pic_wrap" id=" showPic'+count+'" onmouseover="overDelete(this)" onmouseleave="leaveDelete(this)">'+
                '<img  src="'+imgRUL+'"" class="img img-rounded">'+
                '<div class="delete"><img src="/public/html/images/x_alt.png" onclick="deletePic(this)"></div>'+
                '</div>';

        /*遍歷除去最新一個file的所有file,如果有file的值與最後一個file的值相等,不插入預覽圖*/

        for(var i=0;i< $('input[type=file]').length-1;i++){
            var val= $('input[type=file]').eq(i).val();


            if($('input[type=file]').last().val()==val){

                /*此處不插入圖片,就讓count回到之前那一步,否則id=file和id=showPic的資料字尾對不上,導致file和圖片對應錯亂*/
                count=count-1;
                return;
            }
        }

        $('.img_wrap').append(picText);

    }



    /*建立新的file元素*/
    function createFile() {

        var flieText='<input type="file" name="image[]" id="file'+(count+1)+'" style="z-index: '+(count+1)+'" onchange="getPhoto(this)">';

        /*遍歷除去最新一個file的所有file,如果有file的值與最後一個file的值相等,提示圖片已存在,清空最後一個file*/

        for(var i=0;i< $('input[type=file]').length-1;i++){
            var val= $('input[type=file]').eq(i).val();

            if($('input[type=file]').last().val()==val){
                var file = $('input[type=file]').last();
                file.after(file.clone().val(""));
                file.remove();
                alert("圖片已存在!");
                return;
            }
        }


        $('.addbtn_wrap').append(flieText);


        /*圖片數量大於1,顯示提交按鈕,新增一次判斷一次*/
        if($('.pic_wrap').length<=0){

            $('input[type=submit]').css('display','none');
        }else {
            $('input[type=submit]').css('display','block');
        }
    }



    /*移入移出,刪除遮罩層顯示隱藏*/
    function overDelete(obj) {
        $(obj).children('div').show();
    }

    function leaveDelete(obj) {
        $(obj).children('div').hide();
    }



    /*刪除圖片和對應的file*/
    function deletePic(obj) {

        /*提取圖片的id的數字部分*/
        var picId=$(obj).parent().parent().attr('id');

        var picVal= picId.replace(/[^0-9]/ig,"");

        var fileArr=$('input[type=file]');

        /*遍歷file,如果圖片id的數字部分和file的id的數字部分相同,那麼檔案與圖片是對應的,刪除圖片的同時刪除對應的file*/

        fileArr.each(function () {

            /*提取file的id的數字部分*/
            var fileId=$(this).attr('id');
            var fileVal = fileId.replace(/[^0-9]/ig,"");
            if(fileVal==picVal){
                $(this).remove();
                $(obj).parent().parent().remove();
            }
        });

        /*圖片數量大於1,顯示提交按鈕,刪除一次判斷一次*/

        if($('.pic_wrap').length<=0){

            $('input[type=submit]').css('display','none');

        }else {
            $('input[type=submit]').css('display','block');
        }
    }


</script>

tp5控制器程式碼:


    public function doUpload(){

        $files = request()->file('image');

        $info="";
        foreach($files as $picFile){

            // 移動到框架應用根目錄/public/uploads/ 目錄下
            $info = $picFile->move(ROOT_PATH.'uploads'.DS.'images');


            /*獲取儲存路徑,以便插入資料庫*/
           /* $path= "/uploads/images/".$info->getSaveName();*/

        }

 
if($info!==""){
            return $this->success('上傳成功!');
            // 成功上傳後 獲取上傳資訊
            // 輸出 jpg
            /* echo $info->getExtension();*/
            // 輸出 42a79759f284b767dfcb2a0197904287.jpg
            /*echo $info->getFilename();*/
        }else{
            // 上傳失敗獲取錯誤資訊
            /* echo $file->getError();*/


            return $this->error('上傳失敗!');
        }