jquery之图片上传

时间:2024-08-12 16:34:44
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<jsp:include page="/jsp/common/header.jsp"></jsp:include>
<jsp:include page="/jsp/common/common_upload.jsp"></jsp:include>
<script src="${ctx }/js/homepage/home_page_img.js"></script>
<script type="text/javascript">
    $(function() {
        $("#divStatus").hide();
        initSWFUpload({
            flash_url : "${ctx }/js/lib/SWFUpload/Flash/swfupload.swf",
            upload_url: "${ctx }/page/ecUpload/pic/homepage",
            file_post_name:'uploadFile',
            use_query_string:true,
            post_params: {"uploadUserId":"<%=session.getAttribute("userId")%>"},
            file_size_limit : "10 MB",
            file_types : "*.jpg;*.gif;*.png",
            file_types_description : "All Files",
            file_upload_limit : 100,
            file_queue_limit : 0,
            custom_settings : {
                progressTarget : "fsUploadProgress",
                cancelButtonId : "btnCancel"
            },
            debug : false,

            // Button settings
            button_image_url : appPath + "/js/lib/SWFUpload/images/uploadall.png",
            button_width : "61",
            button_height : "22",
            button_placeholder_id : "spanButtonPlaceHolder",
            button_text : '<span class="theFont"></span>',
            button_text_style : ".theFont { font-size: 16; }",
            button_text_left_padding : 12,
            button_text_top_padding : 3,
            button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,

            file_queued_handler : fileQueued,
            file_queue_error_handler : fileQueueError,
            file_dialog_complete_handler : fileDialogComplete,
            upload_start_handler : uploadStart,
            upload_progress_handler : uploadProgress,
            upload_error_handler : uploadError,
            upload_success_handler : uploadPicSuccess,
            upload_complete_handler : uploadComplete,
            queue_complete_handler : queueComplete
        });
    });
</script>
<!-- 判断类型 -->
<input type="hidden" id="imgType" name="imgType" value="<%=request.getParameter("imgType")%>">
<table class="queryTable">
    <tr>
        <td class="queryTitle" width="80px">图片链接</td>
        <td class="queryContent"><input class="inputText" type="text"
            id="queryUrl" /></td>
        <td class="queryTitle" width="80px">图片标题</td>
        <td class="queryContent"><input class="inputText" type="text"
            id="queryImageTopic" /></td>

        <td class="queryBtnTd"><a href="javascript:void(0)"
            class="easyui-linkbutton" iconCls="icon-search" onclick="doQuery()">检索</a>
        </td>
    </tr>
</table>

<table id="queryImgShow" style="display:none">
    <tr>
    <td class="queryTitle" style="font-size:13px; background:white;border:0px" width="80px" valign="top">排序规则</td>
    <td ><img id="imgOrderShow" width="350px" height="350px"
    alt="" src="" /></td>
    </tr>
</table>

<table id="queryInfoGrid"></table>

<div id="addDlg" class="easyui-window" title="" closed="true"
    iconCls="icon-save"
    style="width: 582px; height: 500px; text-align: center; background: #fafafa;">
    <div class="easyui-layout" fit="true">
        <div region="center" border="false"
            style="background: #fff; border: 1px solid #ccc; padding-left: 30px;">
            <form id="addForm" method="POST"
                style="width: 580px; height: 210px; text-align: center;">
                <table id="myTable" border="0" class="queryTable" width="450px" height="210px"
                    style="margin-bottom: 0px">
                    <tr>
                        <td class="queryTitle">排序:<input type="hidden" id="addId" /></td>
                        <td class="queryContent"><input type="text" id="addOrderNum"
                            name="addOrderNum" class="inputText easyui-validatebox" required="true" /></td>
                    </tr>

                    <tr>
                        <td class="queryTitle">上传图片:</td>
                        <td class="queryContent" colspan="30"><span
                            id="spanButtonPlaceHolder"></span>&nbsp;&nbsp;&nbsp;&nbsp; <span
                            style="color: red; font-size: 10px" id="spanSize"></span>
                            <br>
                        <br> <img id="uploadImg"
                            src="${ctx }/images/common/emptyImg.jpg"
                            style="border: solid 1px #ccc; padding: 3px; width: 50px; height: 36px; cursor: hand" />
                            <div id="content">
                                <div id="divStatus">0个文件已经上传</div>
                                <div id="fsUploadProgress"></div>
                                <input id="btnCancel" type="button" value="Cancel All Uploads"
                                    onclick="swfu.cancelQueue();" disabled="disabled"
                                    style="margin-left: 2px; font-size: 8pt; height: 25px; display: none" />
                                <span id="batchNoUploadId" style="display: none;"></span>
                            </div> <input type="hidden" id="imageUrl" name="imageUrl" class="inputText" />
                        </td>
                    </tr>
                    <tr>
                        <td class="queryTitle">广告链接:</td>
                        <td class="queryContent"><input type="text" id="addUrl"
                            name="addUrl" class="inputText easyui-validatebox" required="true" /> <font color="red" id="tag" style="display: none">(必须以http://开头)</font></td>
                    </tr>
                    <tr>
                        <td class="queryTitle">图片标题:</td>
                        <td class="queryContent"><input type="text" id="addImageTopic"
                            name="addImageTopic" class="inputText easyui-validatebox" required="true" /></td>
                    </tr>
                    <tr>
                        <td class="queryTitle" width="70px">开始时间:</td>
                        <td class="queryContent"><input  type="text" id="addbegintime" style="width: 125px" editable="false" /></td>
                    </tr>
                    <tr>
                        <td class="queryTitle" width="70px">结束时间:</td>
                        <td class="queryContent"><input  type="text" id="addendtime" style="width: 125px" editable="false" /> <font color="red">(选填)</font></td>
                    </tr>

                </table>
            </form>
        </div>
        <div region="south" border="false"
            style="text-align: center; height: 30px; line-height: 30px;">
            <a class="easyui-linkbutton" iconCls="icon-ok"
                href="javascript:void(0)" onclick="save()">保存</a> <a
                class="easyui-linkbutton" iconCls="icon-cancel"
                href="javascript:void(0)" onclick="closeWin('addDlg')">关闭</a>
        </div>
    </div>
</div>

<img id="showImgDetail"
    style="position: absolute; display: none; border: 1px #EEEEFF solid;"
    alt="" src="" />
var flag=false;
$(function() {
    $("#addDlg").window("close");
    $("#addUrl").blur(function(){
        if(flag){
            $("#addUrl").css("border-color","#A4BED4");
            flag=false;
        }
      });
     //日期控件
      $('#addbegintime').datetimebox({
            showSeconds:true,
            editable:false
      });
      $('#addendtime').datetimebox({
            showSeconds:true,
            editable:false
      });
      var pageImg = new Object();
      pageImg.codeId=Number($("#imgType").val());
      pageImg.codeType="homePageImgOrder";
        doAjax({
            url : appPath + '/page/pageIndexMrgAct/getImgConfig',
            type : 'post',
            data : pageImg,
            dataType : 'json',
            success : function(data) {
                if(data.code==0){
                    if(data.data.url!=null && data.data.url!=''){
                        $("#imgOrderShow").attr("src", data.data.url);
                        $("#queryImgShow").show();
                    }
                };
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                $.messager.alert('提示信息', '操作未能完成' + textStatus, 'error');
            }
        });

    $("#queryInfoGrid")
            .datagrid(
                    {
                        url : appPath + "/page/pageIndexMrgAct/getImgPage/",
                        height : "full",
                        idField : 'id',
                        striped : true,
                        remoteSort : false,
                        pagination : true,
                        rownumbers : true,
                        singleSelect : false,
                        queryParams : getQueryParam(),
                        frozenColumns : [ [
                                {
                                    field : 'ck',
                                    checkbox : true
                                }

                                 ] ],
                        columns : [ [
                                {
                                    field : 'orderNum',
                                    title : '排序',
                                    width : 100,
                                    align : 'center',
                                    sortable : true,
                                    formatter:function(value,rowData,rowIndex){
                                         var obj=JSON.stringify(rowData);
                                          return "<input type='text' id='orderNum"+rowIndex+"' style='width: 76px;'  value='"+value+"' onchange='onblus(this,"+obj+")'/>";
                                   }
                                },
                                {
                                    field : 'opt',
                                    title : '操作',
                                    width : 40,
                                    align : 'center',
                                    formatter : function(value, rowData,
                                            rowIndex) {
                                         var html="<img class='op-enable' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' onClick='showWin("+rowData.id+")' title='修改'/>"+
                                            "&nbsp;&nbsp;<img class='op-enable' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/cancel.png' onClick='cancel("+rowData.id+")' title='删除'/>";
                                            return html;

                                    }},
                                    {
                                        field : 'imageUrl',
                                        title : '图片',
                                        width : 80,
                                        align : 'center',
                                        sortable : false,
                                        formatter : function(value, rowData,
                                                rowIndex) {
                                            if (value == null || value == '') {
                                                return "<img  border='0' src='"
                                                        + appPath
                                                        + "/js/lib/jquery-easyui/themes/icons/blank.gif"
                                                        + "' />";
                                            } else {
                                                return "<img title='显示图片'  onMousemove=\"mouseOn(event)\"  onmouseout='mouseOff()' rel='"
                                                        + rowData.imageUrl
                                                        + "' src='"
                                                        + appPath
                                                        + "/js/lib/jquery-easyui/themes/icons/search.png"
                                                        + "' />";
                                            }
                                        }
                                    },
                                {
                                    field : 'url',
                                    title : '广告链接',
                                    width : 200,
                                    align : 'center',
                                    sortable : false
                                },
                                {
                                    field : 'imageTopic',
                                    title : '图片标题',
                                    width : 100,
                                    align : 'center',
                                    sortable : false
                                },
                                {
                                    field : 'time',
                                    title : '开始/结束时间',
                                    width : 300,
                                    align : 'center',
                                    sortable : false,
                                    formatter : function(value, rowData, rowIndex) {
                                        if(rowData.endTime!=null){
                                            value=rowData.beginTime+" - "+rowData.endTime;
                                        }else{
                                            value=rowData.beginTime+" - 2099-12-30 23:59:59";
                                        }
                                        return value;
                                    }
                                }
                                ] ],
                        toolbar : [ {
                            id : 'btnadd',
                            text : '新增图片',
                            iconCls : 'icon-add',
                            handler : function() {
                                showWin(null);
                            }
                        }, {
                            id : 'btndel',
                            text : '批量删除图片',
                            iconCls : 'icon-close',
                            handler : function() {
                                deletes();
                            }
                        } ]
                    });
});

function getQueryParam() {
    var pageIndexImg = new Object();
        pageIndexImg.imageType=Number($("#imgType").val());
        pageIndexImg.url= $.trim($('#queryUrl').val());
        pageIndexImg.imageTopic=$.trim($('#queryImageTopic').val());
    return pageIndexImg;
}

function doQuery() {
    $("#queryInfoGrid").datagrid('load', getQueryParam());
}

function deletes() {
    var selections = $("#queryInfoGrid").datagrid('getSelections');
    if (selections == null || selections == '') {
        $.messager.alert('提示信息', '请选择要删除的行', 'info');
        return;
    } else {
        var ids = '';
        for ( var i = 0; i < selections.length; i++) {
            ids += selections[i].id + ',';
        }
        $.messager.defaults = { ok: "确定", cancel: "取消" };
        $.messager.confirm('提示信息', "您将删除选中的全部图片!", function(r) {
            if (r) {
                $.post(appPath + "/page/pageIndexMrgAct/batchDelete", {
                    "ids" : ids,
                    "imageType":Number($("#imgType").val())
                }, function(data) {
                    if(data.code==0){
                        $.messager.alert('提示信息', '删除成功', 'info');
                        doQuery();
                    }else{
                        $.messager.alert('提示信息', data.msg+',操作失败', 'error');
                    }
                });
            }
        });
    }
}

// 图片显示,鼠标移入事件
function mouseOn(e) {
    if ($("#showImgDetail").not(":visible")) {
        var dom = e.srcElement || e.target;
        var tp = $(dom).offset().top;
        var lf = $(dom).offset().left + $(dom).width() + 10;
        $("#showImgDetail").attr("src", $(dom).attr("rel"));
        $("#showImgDetail").css("top", tp);
        $("#showImgDetail").css("left", lf);
        $("#showImgDetail").show();
    }
}

// 图片显示,鼠标移出事件
function mouseOff() {
    $("#showImgDetail").hide();
}

//填写顺序 后实时保存
function onblus (obj,data){
   var orderNum = $(obj).attr("value");
  if(orderNum==null || orderNum==''){
      $(obj).attr("value",data.orderNum);
      return;
  }
  var flag2=validateNum(orderNum);
    if(!flag2){
        $.messager.alert('提示信息','排序请填写正确的0~99之间的自然数','info',function(){
            $(obj).attr("value",data.orderNum);
            $(obj).focus();
        });
        return;
    }

    var pageIndexImg = new Object();
    pageIndexImg.orderNum=orderNum;
    pageIndexImg.imageType=Number($("#imgType").val());
    pageIndexImg.id=data.id;
   doAjax({
        url : appPath + '/page/pageIndexMrgAct/update',
        type : 'post',
        data : pageIndexImg,
        success : function(data) {
            if (data.code != 0) {
                $.messager.alert('提示信息', data.msg + ',操作失败', 'error');
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            $.messager.alert('提示信息', '排序保存失败' + textStatus, 'error');
        }
    });

}

function showWin(id) {
    $("#spanSize").html("");
    $("#addId").val("");
    $("#addOrderNum").val("");
    $("#addImageTopic").val("");
    $("#addUrl").val("");
    $("#imageUrl").val("");
    $("#uploadImg").attr("src", appPath + "/images/common/emptyImg.jpg");
    $("#addbegintime").datebox("setValue","");
    $("#addendtime").datebox("setValue","");
    var param=new Object();
    param.codeId=Number($("#imgType").val());
    param.codeType="homePageImgSize";
    doAjax({
        url : appPath + '/page/pageIndexMrgAct/getImgConfig',
        type : 'post',
        data : param,
        dataType : 'json',
        success : function(data) {
            if(data.code==0){
                if(data.data.words!=null && data.data.words!=''){
                   $("#spanSize").html("(建议尺寸:"+data.data.words+")");
                }
                if(data.data.url=='check'){
                    $("#tag").show();
                }
                if(data.data.standby1=='hideTime'){
                    $("#myTable tr:gt(3)").hide();
                }
            };
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            $.messager.alert('提示信息', '操作未能完成' + textStatus, 'error');
        }
    });
    var iconStr = "icon-add";
    var title = "添加图片";
    if (id != null) {
        iconStr = "icon-edit";
        title = "编辑图片";
        doAjax({
            url : appPath + '/page/pageIndexMrgAct/getImgById',
            type : 'post',
            data : {
                id : id
            },
            dataType : 'json',
            success : function(data) {
                $("#addId").val(data.data.id);
                $("#addImageTopic").val(data.data.imageTopic);
                $("#addOrderNum").val(data.data.orderNum);
                $("#imageUrl").val(data.data.imageUrl);
                $("#addUrl").val(data.data.url);
                $("#uploadImg").attr("src", data.data.uploadUrl);
                $("#addbegintime").datebox("setValue",data.data.beginTime);
                $("#addendtime").datebox("setValue",data.data.endTime);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                $.messager.alert('提示信息', '操作未能完成' + textStatus, 'error');
            }
        });
    }

    $('#addDlg').window({
        title : title,
        iconCls : iconStr,
        width : 580,
        height : 300,
        left : 200,
        modal : true,
        shadow : true,
        collapsible : false,
        minimizable : false,
        maximizable : false
    });
    $('#addDlg').window('move', {
        top : 100
    });
    $('#addDlg').window('open');
}

function closeWin(id) {
    if(id='addDlg'){
        if($("#addOrderNum").val()=='' && $("#imageUrl").val()==''
            && $("#addUrl").val()=='' && $("#addImageTopic").val()==''
                && $("#addbegintime").datebox("getValue")=='' && $("#addendtime").datebox("getValue")==''){
            $('#'+id).window('close');
        }else{
            $.messager.defaults = { ok: "是", cancel: "否,继续填写" };
            $.messager.confirm('提示信息','将丢失已经填写的内容,是否继续关闭?',function(r){
                if(r){
                    $('#'+id).window('close');
                }
            });
        }
    }else{
        $('#'+id).window('close');
    }

}

function save() {
    if ($("#addOrderNum").val() == null || $("#addOrderNum").val() == '') {
        $.messager.alert('提示信息', '请填写排序', 'info');
        return;
    }

    var flag2=validateNum($("#addOrderNum").val());
    if(!flag2){
        $.messager.alert('提示信息','排序请填写正确的0~99之间的自然数','info');
        return;
    }
    //首页-热搜时,图片非必填项
    if(Number($("#imgType").val()) != 11){
        if ($("#imageUrl").val() == null || $("#imageUrl").val() == '') {
            $.messager.alert('提示信息', '请上传图片', 'info');
            return;
        }
    }
    if ($("#addUrl").val() == null || $("#addUrl").val() == '') {
        $.messager.alert('提示信息', '请填写链接', 'info');
        return;
    }
    if($("#addUrl").val().length>1000){
        $.messager.alert('提示信息', '链接超出规定字符范围(1000以内)', 'info');
        return;
    }

    if(!$("#tag").is(":hidden")){
        if($.trim($("#addUrl").val()).substr(0,7)!='http://'){
            $.messager.alert('提示信息', '链接格式错误,请以http://开头!', 'info');
            $("#addUrl").css('border-color','red');
            flag=true;
            return;
        }
    }
    if ($("#addImageTopic").val() == null || $("#addImageTopic").val() == '') {
        $.messager.alert('提示信息', '请填写标题', 'info');
        return;
    }
    var len=getByteLen($.trim($("#addImageTopic").val()));
    if(len>40){
        $.messager.alert('提示信息', '标题最大40个字符', 'info');
        return;
    }
    if(!$("#myTable tr:gt(3)").is(":hidden")){
        if ($("#addbegintime").datebox("getValue") == null ||$("#addbegintime").datebox("getValue") == '') {
            $.messager.alert('提示信息', '请选择开始时间', 'info');
            return;
        }
    }
    if($("#addendtime").datebox("getValue")!=null
            && $("#addendtime").datebox("getValue") != ''
            && $("#addbegintime").datebox("getValue") > $("#addendtime").datebox("getValue")) {
        $.messager.alert('提示信息','开始时间要小于或等于结束时间','info');
        return false;
    } 

    var pageIndexImg = new Object();
    if($("#addId").val()!=null && $("#addId").val()!=''){
        pageIndexImg.id=$("#addId").val();
    }
    pageIndexImg.imageType=Number($("#imgType").val());
    pageIndexImg.orderNum= $.trim($('#addOrderNum').val());
    pageIndexImg.imageUrl=$.trim($("#imageUrl").val());
    pageIndexImg.url=$.trim($("#addUrl").val());
    pageIndexImg.imageTopic=$.trim($("#addImageTopic").val());
    pageIndexImg.beginTime=$("#addbegintime").datebox("getValue");
    if($("#addendtime").datebox("getValue") != null && $("#addendtime").datebox("getValue") != ''){
        pageIndexImg.endTime=$("#addendtime").datebox("getValue");
    }
    doAjax({
        url : appPath + '/page/pageIndexMrgAct/opreatePageIndexImg',
        type : 'post',
        data : pageIndexImg,
        success : function(data) {
            if (data.code == 0) {
                $.messager.alert('提示信息', '保存成功', 'success');
                $('#addDlg').window('close');
                doQuery();
            } else {
                $.messager.alert('提示信息', data.msg + ',操作失败', 'error');
            }
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            $.messager.alert('提示信息', '操作未能完成' + textStatus, 'error');
        }
    });
}

function cancel(id){
    var pageIndexImg = new Object();
    pageIndexImg.id=id;
    pageIndexImg.imageType=Number($("#imgType").val());
    pageIndexImg.isDelete='Y';
    $.messager.defaults = { ok: "确定", cancel: "取消" };
    $.messager.confirm('提示信息','您确定要删除?',function(r){
        if(r){
        doAjax({
            url : appPath + '/page/pageIndexMrgAct/update',
            type : 'post',
            data : pageIndexImg,
            success : function(data) {
                if (data.code == 0) {
                    $.messager.alert('提示信息', '删除成功', 'success');
                    doQuery();
                } else {
                    $.messager.alert('提示信息', data.msg + ',操作失败', 'error');
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                $.messager.alert('提示信息', '操作未能完成' + textStatus, 'error');
            }
        });
        }
    });
}

// 图片上传成功事件
function uploadPicSuccess(file, serverData) {
    try {
        try {
            serverData = eval("(" + serverData + ")");
            if (typeof (serverData.code) != "undefined" && serverData.code != 0) {
                this.uploadError(file, serverData.code, serverData.msg);
            } else {
                var path = serverData.newFileName;
                $("#uploadImg").attr("src", "http://img01.j1.com" + path);
                $("#imageUrl").val("http://img01.j1.com" + path);
                var progress = new FileProgress(file,
                        this.customSettings.progressTarget);
                progress.setComplete();
                progress.setStatus("完成.");
                progress.toggleCancel(false);
            }
        } catch (e) {
            var progress = new FileProgress(file,
                    this.customSettings.progressTarget);
            progress.setComplete();
            progress.setStatus("完成.");
            progress.toggleCancel(false);
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function validateNum (obj){
    var reg =/^\d{1,2}$/;;
    if (!reg.test(obj)) { 

        return false;
    }
    return true;
}

//返回val的字节长度
function getByteLen(val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/ig) != null) //全角
            len += 2;
        else
            len += 1;
    }
    return len;
}