实现多图批量上传

27 篇文章 0 订阅

说明
最近做的一个项目,类似贴吧,用户可发表言论,并上传图片,涉及多图批量上传问题,由于设计图已订好的缘故,插件不太好使用,综合前人经验,自我总结整理出一个比较简单的方法,有利有弊,后期慢慢改良~

示例

style.css

@charset "utf-8";
/* CSS Document */

body{ font:12px/24px "Microsoft YaHei","微软雅黑"; color:#666; background-color:#dcdddd; word-wrap:break-word;max-width: 750px;margin: 0 auto;}
*{ margin:0; padding:0; -webkit-tap-highlight-color:rgba(0,0,0,0);    -webkit-overflow-scrolling: touch;}
ul,ol,li{ list-style:none outside;}
.nowrap{ white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}
a{ color:#666; text-decoration:none;}
a:hover{ text-decoration:none;}
.left{ float:left;}
.right{ float:right;}
.center{ text-align:center;}
.tx_l{ text-align:left;}
.tx_r{ text-align:right;}
.tx_2{ text-indent:2em;}
.bold{ font-weight:bold;}
img{ border:medium none; vertical-align:middle;}
textarea{ resize:none; vertical-align:middle;}
input,button,select,textarea{ -webkit-appearance:none; border:medium none; background:none; outline:none; font:1em/normal "Microsoft YaHei","微软雅黑";}
.btn{ cursor:pointer;}
.clearfix { *zoom: 1; } 
.clearfix:before, .clearfix:after { display: table; line-height: 0; content: ""; } 
.clearfix:after { clear: both;} 

.align_right{text-align: right;}

html,body{font-size: 62.5%;}
html, body {width: 100%;height: 100%;overflow: hidden;}
.wrapper{width: 100%;height: 100%;display: -webkit-flex;flex-direction: column;overflow:hidden;}
.content{width: 100%;height: auto;-webkit-flex:1;flex: 1;box-sizing: border-box;overflow-y:scroll;}

.bg1{background: #dcdddd url(../images/bg1.jpg) no-repeat bottom center;-webkit-background-size:100% 100%;}
.inter_box{width: 90%;margin: 0 auto; padding-top: 150px;}
.inter_d1_load_title{padding: 10px 0 6px 0;display: -webkit-flex;justify-content: space-between;font-size: 1.3rem;line-height: 20px;color: #3e8b34;}
.inter_d1_load_title a{color: #3e8b34;}
.inter_d1_load_title .load_icon{background: url(img/load_icon.png) no-repeat left center;-webkit-background-size:18px 16px;padding-left: 19px;}
.inter_d1_load_box{width: 100%;border: 1px solid #408c34;border-radius: 8px;padding: 6px 2% 0;box-sizing: border-box;}
.inter_d1_loadimg{width: 31%;float: left;margin: 0 1% 5px;position: relative;}
.inter_d1_loadimg img{width: 100%;height: 64px;}
.inter_d1_loadimg  img.load_close{width: 10px;height: 10px;position: absolute;top: 0;right: 0;}
/*input file*/
.imgfile{position: absolute; top: 0; left: 0; width: 100%; height: 64px; z-index: 1; opacity: 0;}
/*load box*/
.loading_box {font-size:16px; line-height:35px; color:#3e3a39; height:40px; text-align:center; padding:30px 0;margin-top:2px;position: absolute;top:40%;left:35%;display:none;}
.pop_cover{width: 100%; height: 100%; background: rgba(0,0,0,0.2); position: fixed; top: 0; left: 0;}
.wid30 { width:35px; height:35px; vertical-align:middle; margin-right:8px;z-index:999;}

html 代码片段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <title>多图批量上传</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/ajaxfileupload.js"></script>
    <script type="text/javascript" src="js/upload.js"></script>
</head>
<body>
    <div class="wrapper">
        <div class="content bg1">
            <div class="inter_box">
                <div class="inter_d1_load">
                    <div class="inter_d1_load_title">
                        <span>图片</span>
                        <input type="hidden" id="pic_urls" />
                        <input type="hidden" id="pic_num" value="0"/>
                        <input type="hidden" id="is_upload" value="1"/>
                        <a href="javascript:void(0)" class="load_icon" id="load_icon" onclick="saveImg(this);">上传</a>
                    </div>
                    <div class="inter_d1_load_box clearfix">
                        <div id="imgdiv">

                        </div>
                        <div class="inter_d1_loadimg" id="remind">
                            <img src="img/load_img.png">
                            <!-- 注:file input 表单必须填写name属性,否则后台获取$_FILES会为null -->
                            <input type="file" class="imgfile" name="files[]" id="files" onchange="uploadImg();" accept="image/*" multiple="multiple" />
                        </div>
                        <div class="loading_box" id="loading_box">
                            <div class="pop_cover"></div>
                            <img class="wid30" src="img/load.gif" />正在上传...
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="pop_txt_box2" id="msg">success</div>
</body>
</html>

upload.js

//ACE吧-上传图片
function uploadImg()
{
    $.ajaxFileUpload({
       url: "/upload/upload-img",
       secureuri: false,
       fileElementId: "files",
       dataType: "json",
       data:{filetype : 'word'},
       success: function(data, status) {
           if (data.err) {
               $("#msg").html(data.err);
               $("#msg").fadeIn();
               setTimeout(function(){
                    $("#msg").fadeOut();
                }, 1000);
               return false;
           } 
           var files = data.oFileUrls;
           var sHtml = '';
           var num = $("#pic_num").val();//图片数量
           num = parseInt(num);
           var str = $.trim($("#pic_urls").val());//图片路径串
           for (var i in files) {
               sHtml += '<div class="inter_d1_loadimg">'
                     +          '<img src="' + files[i] + '" />'
                     +      '<img src="img/load_close.png" class="load_close" onclick="delImg(\'' + encodeURIComponent(files[i]) + '\', this)">'
                     +  '</div>';
               num = num + 1;
               if (str == '') {
                   str = files[i];
               } else {
                   str += ',' + files[i];
               }
           }
           $('div#imgdiv').append(sHtml);//添加图片html
           $("#pic_num").val(num);//图片数量计算
           $("#pic_urls").val(str);//图片路径赋值
           $("#is_upload").val(0);//图片上传标志 标记为未上传
       },
       error: function(data, status, e) {
           showMsg(e)
       }
   })
}

//删除图片
function delImg(picUrl, obj)
{
    //禁止重复点击
    $(obj).removeAttr('onclick');
    //禁止上传图片
    $("#load_icon").removeAttr('onclick');
    var num = $("#pic_num").val();//图片数量
    var str = $.trim($("#pic_urls").val());//图片路径串
    var url = '/upload/del-img';
    $.post(url, {pic_url : picUrl}, function(data) {
        if (!data.success) {
            showMsg(data.msg);
            $(obj).attr('onclick', 'delImg(\'' + encodeURIComponent(picUrl) + '\', this)');
            //添加上传点击事件
            $("#load_icon").attr('onclick', 'saveImg(this)');
            return false;
        } else {//删除成功,移除图片
            $(obj).parent().remove();
            //图片数量减一
            $("#pic_num").val(parseInt(num)-1);
            //图片路径重赋值
            var arr = str.split(',');
            var index = 0;
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == data.url) {
                    index = i;
                    break;
                }
            }
            arr.splice(index, 1);//删除该图片路径
            $("#pic_urls").val(arr.toString());
            //是否已上传标志 变量赋值
            if ($("#pic_urls").val().length < 1) {
                $("#is_upload").val(1);
            }
            //添加上传点击事件
            $("#load_icon").attr('onclick', 'saveImg(this)');
        }
    }, 'json');
}

//保存图片
function saveImg(obj)
{
    //判断是否已再次上传图片
    var pic_urls = $.trim($("#pic_urls").val());
    if (pic_urls.length < 1) {
        showMsg('请选择图片在点击上传');
        return false;
    }
    //判断是否图片数量过多
    var pic_num = $("#pic_num").val();
    pic_num = parseInt(pic_num);
    if (pic_num < 1) {
        showMsg('请选择图片再点击上传');
        return false;
    }
    var pic_size = $("#pic_size").val();
    pic_size = parseInt(pic_size);
    if (pic_num > pic_size) {
        showMsg('图片最多不超过' + pic_size + '张~');
        return false;
    }

    //禁止重复点击
    $(obj).removeAttr('onclick');
    //显示上传提示效果图
    $("#loading_box").show();
    var pic_ids = $("#pic_ids").val();
    var url = '/upload/save-img';
    var param = {
        pic_type : $("#pic_type").val(),
        sUrls : encodeURIComponent(pic_urls)
    }
    $.post(url, param, function(data) {
        if (!data.success) {
            $("#loading_box").hide();//隐藏上传提示效果图
            showMsg(data.msg);
            $(obj).attr('onclick', 'saveImg(this)');
            return false;
        } else {
            $("#loading_box").hide();//隐藏上传提示效果图
            showMsg(data.msg);
            //赋值pic_ids
            if (!pic_ids) {
                $("#pic_ids").val(pic_ids + ',' + data.pic_ids);
            } else {
                $("#pic_ids").val(data.pic_ids);
            }
            //除去删除按钮
            $("#imgdiv").find('div.inter_d1_loadimg').find('img.load_close').remove();
            $("#pic_urls").val('');//清除已上传图片
            $("#is_upload").val(1);//图片上传标志 标记为已上传
            if (pic_num < pic_size) {//上传按钮事件处理
                $(obj).attr('onclick', 'saveImg(this)');
            } else if (pic_num == pic_size) {//已上传规定图片量,移除上传图片框
                $("#remind").remove();
            }
        }
    }, 'json');

}

//信息提示-可自定义显示时间
function showMsg(msg) 
{
    var t = arguments[1] ? arguments[1] : 1000;
    $("#msg").html(msg);
    $("#msg").fadeIn();
    setTimeout(function(){
        $("#msg").fadeOut();
    }, t);
}

uploadController.php

 public function postUploadImg()
    {
        $iDataType = Input::get('filetype');
        if(!isset($_FILES["files"])){
            echo json_encode(array('err'=>'找不到文件'));
            die;
        }else{
            $aInfo = array();
            //多个文件
            if(is_array($_FILES["files"]['name'])){
                $m = count($_FILES["files"]['name']);
                for($i=0;$i<$m;$i++){
                    $filename = $_FILES["files"]['name'][$i];
                    $filetype = get_filetype($filename);
                    //资料上传类型限制
                    switch ($iDataType){
                        case 'word':
                            if(!in_array($filetype , array("jpg","jpeg","png"))){
                                echo json_encode(array('err'=>'请上传jpg,jpeg,png文件中的一种'));die;
                            }
                            break;
                        default:
                            echo json_encode(array('err'=>'参数错误')); die;
                            break;
                    }
                    if(strpos($filetype , ".php") != FALSE){
                        echo json_encode(array('err'=>'禁止上传脚本文件'));die;
                    }
                    $rand_name = date('YmdHis', time()).rand(1000,9999);
                    $sFileName = $rand_name.'.'.$filetype;
                    $sPath = "upload/$filetype/".date('Ymd',time());
                    $sRealPath = public_path().'/'.$sPath;
                    mkdirs($sRealPath);
                    $filesize = filesize($_FILES["files"]['tmp_name'][$i]);
                    if($filesize>20*1024*1024){
                        echo json_encode(array('err'=>'文件过大,请选择其他上传方式'));
                        die;
                    }
                    $filepath = $sRealPath."/".$sFileName;
                    move_uploaded_file($_FILES["files"]['tmp_name'][$i], $filepath);
                    $sFileUrl = $sPath.'/'.$sFileName;
                    $fileurl = '/'.$sFileUrl;
                    $aInfo[] = $fileurl;
                }
            }else{
                //单个文件
                $filename = $_FILES["files"]['name'];
                $filetype = get_filetype($filename);
                //资料上传类型限制
                switch ($iDataType){
                    case 'word':
                        if(!in_array($filetype , array("jpg","jpeg","png"))){
                            echo json_encode(array('err'=>'请上传jpg,jpeg,png文件中的一种'));die;
                        }
                        break;
                    default:
                        echo json_encode(array('err'=>'参数错误')); die;
                        break;
                }
                if(strpos($filetype , ".php") != FALSE){
                    echo json_encode(array('err'=>'禁止上传脚本文件'));die;
                }

                $rand_name = date('YmdHis', time()).rand(1000,9999);
                $sFileName = $rand_name.'.'.$filetype;
                $sPath = "upload/$filetype/".date('Ymd',time());
                $sRealPath = public_path().'/'.$sPath;
                mkdirs($sRealPath);
                $filesize = filesize($_FILES["files"]['tmp_name']);
                if($filesize>20*1024*1024){
                    echo json_encode(array('err'=>'文件过大,请选择其他上传方式'));
                    die;
                }
                $filepath = $sRealPath."/".$sFileName;
                move_uploaded_file($_FILES["files"]['tmp_name'], $filepath);
                $sFileUrl = $sPath.'/'.$sFileName;
                $fileurl = '/'.$sFileUrl;
                $aInfo[] = $fileurl;
            }
            //压缩图片尺寸
            $oFileUrls = SchoolBarPicture::compressPic($aInfo);
            $json = array('success'=>true, 'oFileUrls'=>$oFileUrls);
            echo json_encode($json);
            die;
        }
    }

    //保存图片
    public function postSaveImg()
    {
        $iPicType = intval(Input::get('pic_type'));
        $sUrls = explode(',', urldecode(trim(Input::get('sUrls'))));
        $res = Picture::saveImg($iPicType, $sUrls);
        if (!$res) {
            return json_encode(array('success' => false, 'msg' => '图片为空'));
        } else {
            return json_encode(array('success' => true, 'msg' => '图片上传成功', 'pic_ids' => $res));
        }
    }

    //删除图片
    public function postDelImg()
    {
        if (!Input::has('pic_url') || !Input::get('pic_url')) {
            return json_encode(array('success' => false, 'msg' => '该图片不存在'));
        }
        $pic_url = urldecode(trim(Input::get('pic_url')));
        $resArr = Picture::delImg($pic_url);
        $resJson = array('success' => $resArr[0], 'msg' => $resArr[1]);
        if ($resArr) {
            $resJson['url'] = $pic_url;
        }
        return json_encode($resJson);
   }

效果如下

未添加图片:

这里写图片描述

添加图片后:

这里写图片描述

图片上传后:

这里写图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值