上传文件,不依赖 Jquery flash 插件,用到HTML5 input 新属性实现过滤文件格式、同时上传多个文件

1.样式

2.js

3.后台处理

4.效果图

一.样式

<style>
        .divUpload {
            position: relative;
        }

        .divUploadFirst {
            width: 100px;
            height: 36px;
            background: #666666;
            color: #fff;
            text-align: center;
            line-height: 36px;
        }

        .file_input {
            width: 200px; /*因为file-input在部分浏览器中会自带一个输入框,需要双击才可以点击上传,放大后将其定位到div外面就好啦*/
            height: 36px;
            position: absolute;
            left: -100px;
            top: 0;
            z-index: 1;
            -moz-opacity: 0;
            -ms-opacity: 0;
            -webkit-opacity: 0;
            opacity: 0; /*css属性——opcity不透明度,取值0-1*/
            filter: alpha(opacity=0); /*兼容IE8及以下--filter属性是IE特有的,它还有很多其它滤镜效果,而filter: alpha(opacity=0); 兼容IE8及以下的IE浏览器(如果你的电脑IE是8以下的版本,使用某些效果是可能会有一个允许ActiveX的提示,注意点一下就ok啦)*/
            cursor: pointer;
        }
    </style>
  <div class="divUpload">
                                    <div class="divUploadFirst" style="82px;height:34px;border-radius:14px;">上传协议</div>
                                    <input type="file" class="file_input" id="txtUpload" onchange="upload()" accept="image/*" multiple >
                                </div>
  <div class="form-group" style="clear:both">
                            <div id="images">
                            </div>
                        </div>

二 JS

 //上传协议
        function upload() {
            var uploaderUrl = '@Url.Content("~/PetCase/Upload")';  
            var files = document.getElementById("txtUpload").files;
            var fd = new FormData();
            for (var i = 0; i < files.length; i++) {
                fd.append("file["+i+"]", files[i]);                  
            }                    
            fd.append('caseNum', caseNum);
            $.ajax({
                url:uploaderUrl,
                type :"post",
                data:fd,
                dataType: "json",
                cache: false,//上传文件无需缓存
                processData: false,//用于对data参数进行序列化处理 这里必须false
                contentType: false,
                success:function(data){     
                    if(data.length >0){
                        for (var i = 0; i < data.length; i++) {
                            imgPath.push(data[i].imgpath);

                            var html = '<div style="200px;float:left;margin-left: 5px;cursor:pointer"> <div class="sh" ></div><div class="img1"><img src="' + data[i].imgpath + '" style="200px;" /></div></div>'
                            $("#images").append(html);                            
                        }
                        addPichtml();                       
                    }                   
                },
                error:function(){
                    layer.msg('上传发生错误.');
                }
            });
        }
        function addPichtml() {            
            $(".sh").bind('click', function () {
                var $img = $(this).parent().find("img");
                var ipath = $img.attr("src");
                for (var i = 0; i < imgPath.length; i++) {
                    if (imgPath[i] == ipath) {
                        imgPath.splice(i, 1);
                        $(this).parent().remove();
                        DelImgPath(ipath);
                    }
                }
            })

            $(".img1").bind('click', function () {
                var $img = $(this).parent().find("img");
                var ipath = $img.attr("src");
                for (var i = 0; i < imgPath.length; i++) {
                    if (imgPath[i] == ipath) {
                        layer.open({
                            type: 1,
                            title: "协议",
                            content: '<div><img  src="' + ipath + '" /></div>',
                            maxmin: true,
                            area: [1000 + "px", 600 + "px"]
                        })
                    }
                }
            })

        }

三 后台处理

[HttpPost]
        public ActionResult Upload(HttpPostedFileBase Filedata, string caseNum)
        {
            // 没有文件上传,直接返回
            //if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
            //{
            //    return HttpNotFound();
            //}

            #region 另外一种方式上传
            if (Request.Files == null || Request.Files.Count == 0)
            {
                return HttpNotFound();
            }

            List<object> result = new List<object>();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                Filedata = Request.Files[i];
                #endregion

                string FileEextension = Path.GetExtension(Filedata.FileName);
                string uploadYear = DateTime.Now.Year.ToString();
                string uploadDate = DateTime.Now.Date.ToString("MMdd");

                // string dirpath = System.Configuration.ConfigurationManager.AppSettings["WebTransferHospitalImgDirPath"];
                string filepath = System.Configuration.ConfigurationManager.AppSettings["UploadProtocolPath"];
                string strGUID = System.Guid.NewGuid().ToString();
                strGUID = DateTime.Now.ToString("yyyMMddHHmmssfffffff")+Guid.NewGuid();//上传的图片按上传时间的先后来命名,显示再按命名来排序

                string fullFileName = Server.MapPath("~/UploadFile/UploadProtocol") + "/" + uploadYear + "/" + uploadDate + "/" + caseNum + "/" + strGUID + FileEextension;
                string webPath = filepath + "/" + uploadYear + "/" + uploadDate + "/" + caseNum + "/" + strGUID + FileEextension;

                //创建文件夹,保存文件
                string path = Path.GetDirectoryName(fullFileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                Filedata.SaveAs(fullFileName);

                var data = new { imgpath = webPath };
                result.Add(data);
            }
           
           
            return Json(result, JsonRequestBehavior.AllowGet);
        }

四 效果图

 

天生我材必有用,千金散尽还复来
原文地址:https://www.cnblogs.com/ligenyun/p/8892771.html