zoukankan      html  css  js  c++  java
  • 多张图片的上传

    视图内容:

      <tr>
                            <th><label for="">展示详情图</label> : </th>
                            <td>
                                <div class="">
                                    <!--照片添加-->
                                    <div class="z_photo">
                                        <div class="z_file">
                                            <input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" multiple onchange="filePictureChange()" />
                                        </div>
                                        @{
                                            if (ViewBag.Piclist != null)
                                            {
                                                foreach (var item in ViewBag.Piclist)
                                                {
                                                    <div class="z_addImg">
                                                        <img src="@item.PicUrl" name="ViewSpotPic">
                                                    </div>
                                                }
                                            }
                                        }
                                    </div>
    
                                    <!--遮罩层-->
                                    <div class="z_mask">
                                        <!--弹出框-->
                                        <div class="z_alert">
                                            <p>确定要删除这张图片吗?</p>
                                            <p>
                                                <span class="z_cancel">取消</span>
                                                <span class="z_sure">确定</span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <span class="add_important_tips add_tips">用于展示景区或酒店的细节图片</span>
                            </td>
                        </tr>

    CSS:

    <style>
        .z_photo {
            width: 6rem;
            height: 5rem;
            padding: 0.3rem;
            overflow: auto;
            clear: both;
            border: 1px solid #e5e5e5;
        }
    
            .z_photo img {
                width: 1rem;
                height: 1rem;
            }
    
        .z_addImg {
            float: left;
            margin-right: 0.2rem;
        }
    
        .z_file {
            width: 1rem;
            height: 1rem;
            background: url(/Content/ZLHW/images/z_add.png) no-repeat;
            background-size: 100% 100%;
            float: left;
            margin-right: 0.2rem;
        }
    
            .z_file input::-webkit-file-upload-button {
                width: 1rem;
                height: 1rem;
                border: none;
                position: absolute;
                outline: 0;
                opacity: 0;
            }
    
            .z_file input#filePicture {
                display: block;
                width: auto;
                border: 0;
                vertical-align: middle;
            }
        /*遮罩层*/
    
        .z_mask {
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, .5);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 999;
            display: none;
        }
    
        .z_alert {
            width: 3rem;
            height: 2rem;
            border-radius: .2rem;
            background: #fff;
            font-size: .24rem;
            text-align: center;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -1.5rem;
            margin-top: -2rem;
        }
    
            .z_alert p:nth-child(1) {
                line-height: 1.5rem;
            }
    
            .z_alert p:nth-child(2) span {
                display: inline-block;
                width: 49%;
                height: .5rem;
                line-height: .5rem;
                float: left;
                border-top: 1px solid #ddd;
            }
    
        .z_cancel {
            border-right: 1px solid #ddd;
        }
    </style>

    JS部分:

     @*产品图片*@
        <script>
            function filePictureChange() {
                $.ajaxFileUpload({
                    url: "/System/PhotoUpload", //用于文件上传的服务器端请求地址
                    type: "post",
                    secureuri: false, //一般设置为false
                    fileElementId: "filePicture", //文件上传空间的id属性
                    dataType: "json", //返回值类型 一般设置为json
                    success: function (data, status) {  //服务器成功响应处理函数
                        var arr = new Array();
                        var str = data.FilePath;
                        //可以用字符或字符串分割
                        arr = str.split(',');
                        var imgArr = [];
                        //存放图片的父级元素
                        var imgContainer = document.getElementsByClassName("z_photo")[0];
                        for (var i = 0; i < arr.length - 1; i++) {
                            imgArr.push(arr[i]);
                            var img = document.createElement("img");
                            img.setAttribute("src", imgArr[i]);
                            img.setAttribute("name", "ViewSpotPic");
                            var imgAdd = document.createElement("div");
                            imgAdd.setAttribute("class", "z_addImg");
                            imgAdd.appendChild(img);
                            imgContainer.appendChild(imgAdd);
                        }
                    },
                    error: function (data, status, e) {  //服务器响应失败处理函数
    
                    }
                });
            };
        </script>
    
        <script type="text/javascript">
            //px转换为rem
            (function (doc, win) {
                var docEl = doc.documentElement,
                    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
                    recalc = function () {
                        var clientWidth = docEl.clientWidth;
                        if (!clientWidth) return;
                        if (clientWidth >= 640) {
                            docEl.style.fontSize = '100px';
                        } else {
                            docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
                        }
                    };
    
                if (!doc.addEventListener) return;
                win.addEventListener(resizeEvt, recalc, false);
                doc.addEventListener('DOMContentLoaded', recalc, false);
            })(document, window);
    
    
    
            function imgRemove() {
                var imgList = document.getElementsByClassName("z_addImg");
                var mask = document.getElementsByClassName("z_mask")[0];
                var cancel = document.getElementsByClassName("z_cancel")[0];
                var sure = document.getElementsByClassName("z_sure")[0];
                for (var j = 0; j < imgList.length; j++) {
                    imgList[j].index = j;
                    imgList[j].onclick = function () {
                        var t = this;
                        mask.style.display = "block";
                        cancel.onclick = function () {
                            mask.style.display = "none";
                        };
                        sure.onclick = function () {
                            mask.style.display = "none";
                            t.style.display = "none";
                        };
    
                    }
                };
            };
    
        </script>
        <script src="~/js/ajaxfileupload.js"></script>
    ajaxfileupload.js文件如下:
    ////文件上传
    //function ajaxFileUpload() {
    //    //图片格式验证
    //    var x = document.getElementById("uploadImage");
    //    if (!x || !x.value) return;
    //    var patn = /.jpg$|.jpeg$|.png$|.gif$/i;
    //    if (!patn.test(x.value)) {
    //        alert("您选择的似乎不是图像文件。");
    //        x.value = "";
    //        return;
    //    }
    
    //    var elementIds = ["uploadImage"]; //flag为id、name属性名
    //    $.ajaxFileUpload({
    //        url: '/System/SaveImage',//上传的url,根据自己设置
    //        type: 'post',
    //        secureuri: false, //一般设置为false
    //        fileElementId: 'uploadImage', // 上传文件的id、name属性名
    //        dataType: 'text', //返回值类型,一般设置为json、application/json
    //        elementIds: elementIds, //传递参数到服务器
    //        success: function (data, status) {
    //            //alert(data);
    //            if (data == "Error1") {
    //                alert("文件太大,请上传不大于5M的文件!");
    //                return;
    //            } else if (data == "Error2") {
    //                alert("上传失败,请重试!");
    //                return;
    //            } else {
    //                //这里为上传并做一下请求显示处理,返回的data是对应上传的文件名
    //                $("#appendContent").append("<img  width='200' height='200' src='" + "../UploadFile/TaskReportImages/" + data + "' onclick='RemoveImg(this)'/>");
    
    //            }
    //        },
    //        error: function (data, status, e) {
    //            alert(e);
    //        }
    //    });
    //}
    ////删除图片
    //function RemoveImg(obj) {
    //    $(obj).remove();
    //}
    
    
    jQuery.extend({
        createUploadIframe: function (id, uri) {
            //create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
            if (window.ActiveXObject) {
                if (typeof uri == 'boolean') {
                    iframeHtml += ' src="' + 'javascript:false' + '"';
    
                }
                else if (typeof uri == 'string') {
                    iframeHtml += ' src="' + uri + '"';
    
                }
            }
            iframeHtml += ' />';
            jQuery(iframeHtml).appendTo(document.body);
    
            return jQuery('#' + frameId).get(0);
        },
        createUploadForm: function (id, fileElementId, data) {
            //create form    
            var formId = 'jUploadForm' + id;
            var fileId = 'jUploadFile' + id;
            var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
            if (data) {
                for (var i in data) {
                    jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
                }
            }
            var oldElement = jQuery('#' + fileElementId);
            var newElement = jQuery(oldElement).clone();
            jQuery(oldElement).attr('id', fileId);
            jQuery(oldElement).before(newElement);
            jQuery(oldElement).appendTo(form);
    
    
    
            //set attributes
            jQuery(form).css('position', 'absolute');
            jQuery(form).css('top', '-1200px');
            jQuery(form).css('left', '-1200px');
            jQuery(form).appendTo('body');
            return form;
        },
    
        ajaxFileUpload: function (s) {
            // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
            s = jQuery.extend({}, jQuery.ajaxSettings, s);
            var id = new Date().getTime()
            var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
            var io = jQuery.createUploadIframe(id, s.secureuri);
            var frameId = 'jUploadFrame' + id;
            var formId = 'jUploadForm' + id;
            // Watch for a new set of requests
            if (s.global && !jQuery.active++) {
                jQuery.event.trigger("ajaxStart");
            }
            var requestDone = false;
            // Create the request object
            var xml = {}
            if (s.global)
                jQuery.event.trigger("ajaxSend", [xml, s]);
            // Wait for a response to come back
            var uploadCallback = function (isTimeout) {
                var io = document.getElementById(frameId);
                try {
                    if (io.contentWindow) {
                        xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                        xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
    
                    } else if (io.contentDocument) {
                        xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                        xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                    }
                } catch (e) {
                    jQuery.handleError(s, xml, null, e);
                }
                if (xml || isTimeout == "timeout") {
                    requestDone = true;
                    var status;
                    try {
                        status = isTimeout != "timeout" ? "success" : "error";
                        // Make sure that the request was successful or notmodified
                        if (status != "error") {
                            // process the data (runs the xml through httpData regardless of callback)
                            var data = jQuery.uploadHttpData(xml, s.dataType);
                            // If a local callback was specified, fire it and pass it the data
                            if (s.success)
                                s.success(data, status);
    
                            // Fire the global callback
                            if (s.global)
                                jQuery.event.trigger("ajaxSuccess", [xml, s]);
                        } else
                            jQuery.handleError(s, xml, status);
                    } catch (e) {
                        status = "error";
                        jQuery.handleError(s, xml, status, e);
                    }
    
                    // The request was completed
                    if (s.global)
                        jQuery.event.trigger("ajaxComplete", [xml, s]);
    
                    // Handle the global AJAX counter
                    if (s.global && ! --jQuery.active)
                        jQuery.event.trigger("ajaxStop");
    
                    // Process result
                    if (s.complete)
                        s.complete(xml, status);
    
                    jQuery(io).unbind()
    
                    setTimeout(function () {
                        try {
                            jQuery(io).remove();
                            jQuery(form).remove();
    
                        } catch (e) {
                            jQuery.handleError(s, xml, null, e);
                        }
    
                    }, 100)
    
                    xml = null
    
                }
            }
            // Timeout checker
            if (s.timeout > 0) {
                setTimeout(function () {
                    // Check to see if the request is still happening
                    if (!requestDone) uploadCallback("timeout");
                }, s.timeout);
            }
            try {
    
                var form = jQuery('#' + formId);
                jQuery(form).attr('action', s.url);
                jQuery(form).attr('method', 'POST');
                jQuery(form).attr('target', frameId);
                if (form.encoding) {
                    jQuery(form).attr('encoding', 'multipart/form-data');
                }
                else {
                    jQuery(form).attr('enctype', 'multipart/form-data');
                }
                jQuery(form).submit();
    
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
    
            jQuery('#' + frameId).load(uploadCallback);
            return { abort: function () { } };
    
        },
    
        uploadHttpData: function (r, type) {
            var data = !type;
            data = type == "xml" || data ? r.responseXML : r.responseText;
            // If the type is "script", eval it in global context
            if (type == "script")
                jQuery.globalEval(data);
            // Get the JavaScript object, if JSON is used.
            if (type == "json")
                eval("data = " + data);
            //eval("data = "" + data + """);
            // evaluate scripts within html
            if (type == "html")
                jQuery("<div>").html(data).evalScripts();
    
            return data;
        },
        handleError: function (s, xhr, status, e) {
            // If a local callback was specified, fire it
            if (s.error) {
                s.error.call(s.context || s, xhr, status, e);
            }
    
            // Fire the global callback
            if (s.global) {
                (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
            }
        },
    })

    控制器

      #region 图片上传
            public ActionResult PhotoUpload()
            {
                log4net.ILog logger = log4net.LogManager.GetLogger("PhotoUpload");
    
                JsonModel jsonModel = new JsonModel();
                jsonModel.Code = "0";
                jsonModel.Message = "上传成功";
                string fileName = "";
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                logger.Error("上传图片数量:" + files.Count);
                for (int i = 0; i < files.Count; i++)
                {
              //通过图片文件转换为图片地址
    string url = TravelB2B.Core.Utils.Tools.HttpPostFileSave("", i, out fileName); if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(fileName)) { //保存数据 SYS_Album_Photo photo = new SYS_Album_Photo(); photo.CreateTime = DateTime.Now; photo.IsCover = 0; photo.Name = fileName; photo.Photo = url; photo.SystemID = CurrentUser.Company.ID; photo.Create(); jsonModel.Code = files.Count.ToString(); jsonModel.Data += url + ","; jsonModel.Message = "上传失败"; } } return Json(new { FileName = fileName, FilePath = jsonModel.Data, FileSize = jsonModel.Code }, "text/html", JsonRequestBehavior.AllowGet); //return Json(jsonModel, JsonRequestBehavior.AllowGet); } #endregion

     

  • 相关阅读:
    [Matlab] 短时傅里叶变换spectrogram函数
    [Word] Word中保存出矢量图
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] 画图颜色扩展
    [脑电相关] 关于ERD现象
    [PPT技巧] PPT箭头设置及文字设置
    linux 新添加的硬盘格式化并挂载到目录下方法
  • 原文地址:https://www.cnblogs.com/hugeboke/p/11573207.html
Copyright © 2011-2022 走看看