图片上传即时预览效果

目前是在做一个用mvc+ef框架开发的项目.  开发WebApi接口来让手机端重用~

一个很简单的功能做出最好的效果.    这个兼容性绝壁很好. 都测试过~ 

要做的效果图:

实现的效果图:

view:

@{
    ViewBag.Title = "Identity";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="nav-box2">
    <div class="nav-cont2">
        <a class="a-listover" title="个人设置" href="javascript:;">个人设置</a>
        <a title="我是雇主" href="javascript:;">我是雇主</a>
        <a title="我是威客" href="javascript:;">我是威客</a>
        <a title="消息通知" href="javascript:;">消息通知</a>
        <a title="我的优惠信息" href="javascript:;">我的优惠信息</a>
        <a class="index-note" href="#">切换至旧网站 >></a>
    </div>
</div>

<div class="cent-cont ">
    @Html.Partial("_Menu")
<div class="fl right-cont">
@using (Html.BeginForm("identity", "my", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
       <div class="uesr-tit mt15 ml25"><strong class="f14">身份认证</strong></div>      
        <div class="reg-cont mt30 ml25 mb20">                       
                <div class="item mt15">
                    <span class="reg-tit2">个人账户:</span>
                    <div class="reg-inf">
                        <input class="inputes reg-input gray-bc" name="txtAccount" value="18665916356" readonly="" type="text">
                    </div>
                </div>
                <div class="item mt15">
                    <span class="reg-tit2"><font class="red">*</font>真实名字:</span>
                    <div class="reg-inf">
                    <input class="inputes reg-input" name="txtRealName" type="text">                 
                    </div>
                    <div class="fl f12 mt15 ml10 gray1">请确保您填写的姓名与身份证原件上的姓名一致。</div>                    
                </div>
                <div class="item mt15">
                    <span class="reg-tit2"><font class="red">*</font>身份证号码:</span>
                    <div class="reg-inf">
                        <input class="inputes reg-input" name="txtIdNumber" type="text">                 
                    </div>
                </div>    
                               
            <div class="item mt15">
                    <span class="reg-tit2"><font class="red">*</font>身份证原件:</span>
                    <div class="reg-inf">   
                        <input type="file" style="display:none" name="firstFile" id="firstFile" onchange="change('firstImg', 'firstFile')">
                        <input type="file" style="display:none" name="lastFile" id="lastFile" onchange="change('lastImg', 'lastFile')">
                        <div class="fl mr15 up-inf"><span onclick="openBrowse('firstFile')">正面单击上传</span><img width="144" height="89" id="firstImg" src="/skin/images/front.png"></div>
                        <div class="fl up-inf"><span onclick="openBrowse('lastFile')">反面单击上传</span><img width="144" height="89" id="lastImg" src="/skin/images/conimg.png"></div>
                        @*<div class="fl mr15 up-inf"><span>正面单击上传</span><img src="../../skin/images/front.png"></div>
                        <div class="fl up-inf"><span>正面单击上传</span><img src="../../skin/images/conimg.png"></div>*@
                        <div class="fl f12 gray1 span270 ml10">
                            <p>证件要求:</p>
                            <p>请上传有效的身份证图片,非证件图片不予受理。</p>
                            <p>1.证件必须是彩色原件电子版,可以是扫描件或者数码拍摄照片。</p>
                            <p>2.仅支持.jpg.bmp.png.gif的图片格式。图片大小不超过2M。</p>
                        </div>  
                    </div>
                </div>               
                <div class="item mt15">
                    <span class="reg-tit2"><font class="red">*</font>身份证到期时间:</span>
                    <div class="reg-inf">
                        <input class="fl inputes long-input" type="text" name="txtDateTime" id="expire">  <input class="fl mt17 ml10" name="checkDateTime" type="checkbox"> <font class="fl f12 mt15 ml5">长期</font>             
                    </div>
                </div>
                <div class="item mt15">
                    <span class="reg-tit2">能力证书上传:</span>
                    <div class="reg-inf">
                        <input type="file" style="display:none" name="tktFile" id="tktFile" onchange="change('tkt', 'tktFile')">
                        <div class="fl mr15 up-inf"><span onclick ="openBrowse('tktFile')">单击上传</span><img id="tkt" width="144" height="89" src="/skin/images/ability.png"></div>
                        <div class="fl f12 gray1 mt30">仅支持.jpg.bmp.png.gif的图片格式,图片大小不超过2M。</div>                              
                    </div>
                </div>
                <div class="item mt15">
                    <span class="reg-tit2">职业:</span>
                    <div class="reg-inf">
                        <select class="span302" name="job">
                            @foreach (YiTask.Model.BasicDataConfig ymbModel in ViewBag.job as List<YiTask.Model.BasicDataConfig>)
                            {
                                <option value="@ymbModel.BasicDataID">@ymbModel.DisplayName</option>
                            }
                        </select>
                    </div>
                </div>
                <div class="item mt15">
                    <span class="reg-tit2">目前住址:</span>
                    <div class="reg-inf">
                    <input class="inputes reg-input" name="txtAdress" type="text">                 
                    </div>
                </div>                                                                                                                                                                                    
            <div class="item"><input class="btn-green f14 ml180 mt20" value="提交" type="submit"></div>                                              
        </div><!--/reg-cont-->       
       
 
}
</div>
    

</div>
        <div class="cl"></div>



<script type="text/javascript" src="/skin/js/laydate/laydate.js"></script>
<script type="text/javascript">
    //使用IE条件注释来判断是否IE6,通过判断userAgent不一定准确
    if (document.all) document.write('<!--[if lte IE 6]><script type="text/javascript">window.ie6= true<\/script><![endif]-->');
    // var ie6 = /msie 6/i.test(navigator.userAgent);//不推荐,有些系统的ie6 userAgent会是IE7或者IE8
    function change(picId,fileId) {
        var pic = document.getElementById(picId);
        var file = document.getElementById(fileId);
        if(window.FileReader){//chrome,firefox7+,opera,IE10,IE9,IE9也可以用滤镜来实现
            oFReader = new FileReader();
            oFReader.readAsDataURL(file.files[0]);
            oFReader.onload = function (oFREvent) {pic.src = oFREvent.target.result;};
        }
        else if (document.all) {//IE8-
            file.select();
            var reallocalpath = document.selection.createRange().text//IE下获取实际的本地文件路径
            if (window.ie6) pic.src = reallocalpath; //IE6浏览器设置img的src为本地路径可以直接显示图片
            else { //非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现,IE10浏览器不支持滤镜,需要用FileReader来实现,所以注意判断FileReader先
                pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
                pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';//设置img的src为base64编码的透明图片,要不会显示红xx
            }
        }
        else if (file.files) {//firefox6-
            if (file.files.item(0)) {
                url = file.files.item(0).getAsDataURL();
                pic.src = url;
            }
        }
    }



    function openBrowse(id) {
        var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false;
        if (ie) {
            document.getElementById("" + id + "").click();
            //document.getElementById("filename").value = document.getElementById("file").value;
        } else {
            var a = document.createEvent("MouseEvents");//FF的处理
            a.initEvent("click", true, true);
            document.getElementById("" + id + "").dispatchEvent(a);
        }
    }


laydate({
    elem: '#expire', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎,因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
    event: 'focus' //响应事件。如果没有传入event,则按照默认的click
});
</script>

 

Controller:

[AcceptVerbs(HttpVerbs.Post)]
        public void Identity(HttpPostedFileBase firstFile, HttpPostedFileBase lastFile, HttpPostedFileBase tktFile, string txtRealName, string txtIdNumber, string txtDateTime, string checkDateTime, string job, string txtAdress)
        {
            Model.ApiResult.PersonalAuthentication paModel = new Model.ApiResult.PersonalAuthentication();
            paModel.UserID = Convert.ToInt32(SessionManager.Instance.UserID);
            paModel.IdNumber = txtIdNumber;
            paModel.RealName = txtRealName;
            paModel.IdNumber = txtIdNumber;
            paModel.PositiveImg = GetImgUrl(firstFile);
            paModel.BackImg = GetImgUrl(lastFile);
            paModel.ExpiryTime = String.IsNullOrEmpty(txtDateTime) ? DateTime.MinValue : Convert.ToDateTime(txtDateTime);
            paModel.Occupation = Convert.ToInt32(job);
            paModel.CurrentAddress = txtAdress;
            paModel.PostDate = DateTime.Now;
            paModel.IDThumbnail = "";
            paModel.State = (int) YiTask.Share.BasicData.审核中;
            paModel.Certificate = GetImgUrl(tktFile);
            var model = paModel;
            Model.ApiResult.IdCardModel imModel = JsonConvert.DeserializeObject<Model.ApiResult.IdCardModel>(ApiHelper.PostApi("/api/pa", model).ToString());
            if (imModel.Message == "提交身份认证信息成功")
            {
                Response.Redirect("/my/identitysubmit");
            }
            else
            {
                Response.Write("<script>alert('" + imModel.Message + "');location.href='/my/identity';</script>");
            }
        }

 

        /// <summary>
        /// 上传图片到服务器
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string GetImgUrl(HttpPostedFileBase fileName)
        {
            string path = Common.ConfigHelper.GetConfigString("picUpload") + "/IdCard";
            string pathWjj = System.DateTime.Now.ToString("yyyyMMdd");
            string root = path + "/" + pathWjj;
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            //上传和返回(保存到数据库中)的路径
            string uppath = string.Empty;
            string savepath = string.Empty;
            //if (Request.Files.Count > 0)
            //{
            if (fileName != null)   
            {
                if (fileName.ContentLength > 0)
                {
                    //创建图片新的名称
                    string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //获得上传图片的路径
                    string strPath = fileName.FileName;
                    //获得上传图片的类型(后缀名)
                    string type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
                    //if (ValidateImg(type))
                    //{
                    //拼写数据库保存的相对路径字符串
                    savepath = pathWjj + "/" + nameImg + "." + type;
                    //拼写上传图片的路径
                    uppath = path + "/" + savepath;
                    //上传图片
                    fileName.SaveAs(uppath);
                    //}
                }
            }
            return savepath;
        }

 

你可能感兴趣的:(图片上传)