uploadify插件实现多个图片上传并预览

使用uploadify插件可方便实现图片上传功能。兼容ie6、ie7。

上传成功之后使用插件的回调函数读取json数据,根据url实现图片预览。

效果图:

图片上传预览效果图

点击浏览文件上传图片,图片依次在右侧显示预览效果。

实现:

json数据格式如下:

json数据

页面代码如下:

注:需要引用jQuery.js、uploadify.js、uploadify文件。。uploadify文件下载地址:http://www.uploadify.com/download/

<html>

<head>

<script type="text/javascript" src="static/js/jquery.js">"></script>

<script type="text/javascript" src="static/js/jquery.select.js">"></script>

</head>

<body>

<div class="file-box"> 
                        <div id="divPreview">
                            <span style="float:left">(最多可上传五张图片)</span>
                        </div>
                        <input type="file" name="file" class="file" id="fileField"  /> 
                        <input type="hidden" name="hash" id="hash" value="xoxo"/> 

</div> 

<script>

$(function() {

   $("#fileField").uploadify({

       'height'        : 30,

        'swf'       : '<?php echoYii::app()->request->baseUrl ?>/static/uploadify/uploadify.swf?var='+(newDate()).getTime(),

       'uploader'      :'index.php?r=upload/uploadimage',

       'width'         : 120,

       'onUploadSuccess' : function(file, data, response) {

            var info = eval("("+data+")");
            if(info.err==1){alert(info.msg);}                                       //如果图片过大或者格式错误弹出错误信息
            else{
            $("#divPreview").append($("<img src='" + info.img + "'/>"));
            $("#divPreview").append($("<input type='hidden' name='imgId[]' value='" + info.imgId + "'/>"));
            }
        },

       'buttonText'    : '浏览文件',

       'uploadLimit'   : 5,                                                                      //上传最多图片张数

       'removeTimeout' : 1,

       'preventCaching': true,                                                           //不允许缓存

       'fileSizeLimit' : 4100,                                                              //文件最大

       'formData'      : { '<?php echosession_name();?>' : '<?php echosession_id();?>','hash':$("#hash").val() }           //hash

   });

   $("#SWFUpload_0").css({                  //设置按钮样式,根据插件文档进行修改

                        'position' :'absolute',

                        'top': 20,

                        'left': 35,

                        'z-index'  : 1

                    });

});

</script>

</body>

</html>

曾遇到问题:

ie、360浏览器中对json数据检查比较严格,不允许最后一个“,”存在。其它浏览器不会报错,需要注意。

原文地址:https://www.cnblogs.com/xingfuboke/p/4920769.html