jquery js自定义上传图片

1. 实现自定义的上传图片控件,如图:

 点击【选择图片】,可预览图片效果,【提交】按钮再把图片,上传到指定目录。

 

2. ASPX 页面代码:

View Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>产品类别编辑</title>
   <link href="../App_Themes/Default/Styels/main.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="../Scripts/messages_cn.js" type="text/javascript"></script>
     <script src="../Scripts/main.js" type="text/javascript"></script>
   <%-- <script src="../Scripts/Comm.js" type="text/javascript"></script>--%>
    <script type="text/javascript">
        $(function () {
            //加载图片上传插件
            $("#btnLoadPhoto").upload({ url: "../UploadForms/RequestUpload.aspx?action=photo", type: "json", callback: calla });
            function calla(a) {
                if (a.errorinfo!=undefined)
                    alert(a.errorinfo);
                else {
                    var savePath = unescape(a.filePath) + unescape(a.fileName);
                    $("#hidimgPhoto").val(savePath);
                    $("#imgPhoto").attr("src", "../" + savePath);
                }
            }

            $("#btnSubmit").click(function () {
                var errorinfo = $("#ValidInfo").html();
                return errorinfo == "" ? true : false;
            });

            $("#txtCategoryName").on("blur", function () {
                var categoryName = $(this).val();
                $.ajax({
                    type: "post",
                    contentType: "application/json",
                    url: "../WebService/CommWebService.asmx/GetNewsCategory",
                    data: "{categoryName:'" + categoryName + "'}",
                    dataType: "json",
                    success: function (result) {
                        if (result.d > 0) {
                            $("#ValidInfo").html("该分类名称已被占用.");
                        } else
                            $("#ValidInfo").html("");
                    }
                });
            });

        });
</script>
</head>
<body id="formPage">

    <form id="form1" runat="server">

<div class="rows">
    <div class="rowChilds">类型名称<span class="starRed">*</span></div>
    <asp:TextBox ID="txtCategoryName" runat="server" class="required" MaxLength="50" Height="20px" Width="180px"></asp:TextBox>
        <label id="ValidInfo" style="color:Red"></label>
       <asp:RequiredFieldValidator ID="RegularExpressionValidator1" runat="server" Display="Dynamic" 
         ControlToValidate="txtCategoryName" ErrorMessage="类型名称不能为空" ForeColor="Red"></asp:RequiredFieldValidator>
</div>
<div class="rows">
    <div class="rowChilds">排序</div>
    <%--<asp:TextBox ID="txtSN" runat="server" Height="20px" Width="180px" MaxLength="10"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" 
        ForeColor="Red" ErrorMessage="请输入整数" ControlToValidate="txtSN" 
        ValidationExpression="^[1-9]\d*|0$"></asp:RegularExpressionValidator>--%>
        <asp:DropDownList runat="server" ID="dpSN"></asp:DropDownList>
</div>
    
    <div class="rows">
    <div class="rowChilds">图片:</div>
     
     <div class="rowChilds rowChildsCW150">
  <asp:Image runat="server" ID="imgPhoto" style="width:120px;height:120px" />
   <div class="rowChilds rowChildsCW150" style="padding-left:40px">

        <input type="button" id="btnLoadPhoto" class="Buttons" value="选择图片..." /> </div>
     
     </div>
</div>
<div class="rows" style="padding-top:10px" >
    <div class="rowChilds">说明:</div>
    <asp:TextBox ID="txtDescription" runat="server" title="说明" Height="50px" 
        TextMode="MultiLine" Width="268px"></asp:TextBox>

</div>
  <div class="rows">
  </div>
<div class="rows">
<buttons:ButtonGroup runat="server" OnPublishClick="btnCreate_Click" ID="ButtonGroup1" 
        OnSubmitClick="btnCreate_Click"  OnDeleteClick="btnDelete_Click" 
        OnDisabledClick="btnDisabled_Click" OnRecoveryClick="btnRecovery_Click" 
        CausesValidationOfDelete="False" CausesValidationOfDisabled="False" 
        CausesValidationOfRecovery="False" IsShowCancel="True"
          />
    <asp:HiddenField ID="hidType" runat="server" />
    <asp:HiddenField ID="hidCategoryId" runat="server" />
    <asp:HiddenField ID="hidimgPhoto" runat="server" ClientIDMode="Static" />
    </div>
    </form>
</body>
 
</html>

 

4. 处理上传文件类代码:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using MideaApp.Core;
namespace MideaApp.Web.UploadForms
{
    public partial class RequestUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Upload();
            }
        }

        /// <summary>
        /// 处理文件上传
        /// </summary>
        private void Upload()
        {
            string errorMsg = string.Empty;
            string action = null;
            action =Request.QueryString["action"];
            string result = "";
            try
            {
                //获得表单元素
                HttpPostedFile oFile = Request.Files[0];
                //设置上传路径
                string strUploadPath = "temp/";
                //获取文件名称
                string fileName = Request.Files[0].FileName;


                #region 判断文件后缀名
                //获取文件后缀名
                string fileExtension = Path.GetExtension(fileName);
                if (action == "pdf")
                {
                    if (!UnitityService.pdfExtension.Contains(fileExtension))
                    {
                        errorMsg = "请选择后缀名是 .pdf 的文件.";
                    }
                }
                if (action == "photo")
                {
                    if (!UnitityService.photoExtension.Contains(fileExtension))
                    {
                        errorMsg = "请选择后缀名是";
                        foreach (string sion in UnitityService.photoExtension)
                        {
                            errorMsg += sion;
                        }
                        errorMsg+="的文件.";
                    }
                }

                #endregion

                fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;
                string savePath = HttpContext.Current.Server.MapPath("~/" + strUploadPath);
                if (oFile != null)
                {
                    //如果指定路径不存在则创建
                    if (!Directory.Exists(strUploadPath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    //保存上传图片
                    oFile.SaveAs(savePath + fileName);
                }
                 string fileSize = CommonHelper.GetFileSize("~/" + strUploadPath + fileName);

                 if (double.Parse(fileSize) > 5 && errorMsg == "" && action == "photo")
                 {
                     errorMsg = "上传文件不能大于5MB.";
                     File.Delete(savePath + fileName);
                 }
                 if (double.Parse(fileSize) > 20 && action == "pdf")
                 {
                     errorMsg = "上传文件不能大于20MB.";
                     File.Delete(savePath + fileName);
                 }

                if (string.IsNullOrEmpty(errorMsg))
                {
                    result = ("{\"fileName\":\"" + CommonHelper.JSEscape(fileName) + "\",\"filePath\":\"" + CommonHelper.JSEscape(strUploadPath) + "\"}");
                }
                else
                {
                    result = ("{\"errorinfo\":\"" +errorMsg + "\"}");
                }
            }
            catch (Exception)
            {
                errorMsg = "上传文件不能大于5MB.";
                result = "{\"errofinfo\":\"" + errorMsg + "\"}";
                //throw;
            }
            Response.Write(result);
        }
    }
}

 

注:关于提交的后台代码

5. main.js 文件

View Code
(function ($) {
    //    $.fn.isEmpty = function (v) {
    //        
    //    };
    $.fn.upload = function (options) {
        var _this = $(this),
        _tId = _this.attr("id"),
        def = {
            formId: "uploadForm" + _tId + $.dateTimeInt(),
            iframeName: "uploadIframe" + _tId + $.dateTimeInt(),
            fileName: "uploadFile" + _tId + $.dateTimeInt(),
            loadingID: "img" + _tId + $.dateTimeInt()
        },
        w = _this.width() + 25;
        w = (w.toString().indexOf("px") > 0 ? w : w + "px");
        $.extend(def, options);
        var form = "<img id=\"" + def.loadingID + "\" style=\"display:none;margin-top:20px;\" src=\"../App_Themes/Default/Images/loading.gif\" alt=\"Loading\"/>" +
             "<form id=\"" + def.formId + "\" enctype=\"multipart/form-data\" method=\"post\" action=\"" + def.url + "\" target=\"" + def.iframeName + "\">" +
            "<div style=\"width:90px;height:22px;overflow:hidden; position:absolute;z-index:2; left:0;top:0\">" +
            "<input type=\"file\" id=\"" + def.fileName + "\" name=\"" + def.fileName + "\" style=\"filter:alpha(opacity:0);opacity:0;" + ($.browser.msie ? "float:right" : "") + "\"/>" +
            "</div><iframe id=\"" + def.iframeName + "\" name=\"" + def.iframeName + "\" src=\"about:blank\" style=\"display:none\"></iframe></form>",
            tDiv = "<div style=\"width:" + w + ";height:auto;overflow:hidden;position:relative\"></div>";
        return this.each(function () {
            var ot = $(tDiv);
            ot.appendTo(_this.parent());
            _this.appendTo(ot);
            $(form).appendTo(ot);
            $("#" + def.fileName).on("change", function () {
                var t = true;
                if (def.change) {
                    t = def.change($("#" + def.fileName));
                }
                if (t) {
                    _this.hide();
                    $("#" + def.loadingID).show();
                    $("#" + def.formId).submit();
                }
            });
            $("#" + def.iframeName).load(function () {
                var oIfm = document.getElementById(def.iframeName).contentWindow.document;
                if (oIfm) {
                    var oBody = $(oIfm.body);
                    if (oBody) {
                        var text = (oBody ? oBody.text() : "");
                        if (def.callback) {
                            var r;
                            def.type = (!def.type ? "text" : def.type);
                            if (def.type === "json") {
                                var fjson = new Function("return " + text);
                                r = fjson();
                            } else {
                                r = text;
                            }
                            if (!$.isEmpty(text)) {
                                def.callback(r);
                            }
                        }
                    }
                    _this.show();
                    $("#" + def.loadingID).hide();
                }
            });
        });
    };
})(jQuery);

$.extend({
    isEmpty: function (s) {
        var p = false, v = (s === undefined ? "" : s);
        if ($.trim(v).length === 0) { p = true; };
        return p;
    },
    dateTimeInt: function () {
        var n = new Date();
        return n.getFullYear().toString() + (n.getMonth() + 1).toString() + n.getDate().toString() + n.getHours().toString() + n.getMinutes().toString() + n.getSeconds().toString();
    },
    createDialog: function (p) {
        if (p) {
            var url = p.url,
            w = (p.width ? p.width : 400),
            h = (p.height ? p.height : 300),
            id = "dialog" + this.dateTimeInt(),
            fid = "frame" + this.dateTimeInt(),
            dw = w,
            dh = h + 20;
            w += "px";
            h += "px";
            var div = "<div id=\"" + id + "\" style=\"width:" + w + ";height:" + h + ";overflow:hidden;\" title=\"" + (p.title ? p.title : "") + "\">",
            iframe = "<iframe id=\"" + fid + "\" scrolling=\"no\" frameborder=\"0\" style=\"width:" + w + ";height:" + h + ";overflow:hidden;\" src=\"" + url + "\"></iframe>";
            div += iframe + "</div>";
            $(document.body).append(div);
            $("#" + fid).load(function () {
                $("#" + id).dialog({ width: dw, height: dh,
                    close: function (event, ui) {
                        $(this).remove();
                        if (p.close) {
                            p.close();
                        }
                    }
                });
            });
            return id;
        }
    },
    closeDialog: function (id) {
        $("#" + id).dialog("close");
    },
    reload: function () {
        window.location.reload();
    },
    removeSpace: function (text) {
        return text.replace(/\s/ig, '');
    }
});

转载于:https://www.cnblogs.com/hyong/archive/2012/07/02/2573559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值