通过Javascript 创建POST提交, 无页面刷新下载

前端准备:

//Download the template through "POST" request
                    function getTargertContainer() {
                        var $tagertContainer = $("#gridviewContainer");
                        if ($("#gridview_Import_dialog").size()) {
                            $tagertContainer = $("#gridview_Import_dialog").parent();
                        }
                        return $tagertContainer;
                    }
                    function downloadExcelTemplate() {
                        var criteria = $("#gridview").data("kendoGrid").options.temp.criteria;
                        criteria.GetIdCollectionOnlyAndIgnorePagination = true;
                        criteria.withData = true;

                        if ($("#iframeforDownload").size()) {
                            $("#iframeforDownload").remove();
                        }
                        $("<iframe frameborder='1' width='0' height='0' src='about:blank' scrolling='no' id='iframeforDownload'>").appendTo("body");
                        var iframe = $("#iframeforDownload");
                        var iframeDocument = iframe[0].contentDocument || iframe[0].contentWindow.document;
                        var content = "<html><head><meta charset='utf-8' /></head><body><form action='/ExcelBulkEdit/DownloadTemplate' method='post'>";
                        for (var prop in criteria) {
                            if (typeof criteria[prop] == "object") {
                                for (var i = 0; i < criteria[prop].length; i++) {
                                    for (var childprop in criteria[prop][i]) {
                                        content += "<input name='" + prop + "[" + i + "]." + childprop + "' type='hidden' value='" + criteria[prop][i][childprop] + "'/>";
                                    }
                                }
                            } else {
                                content += "<input name='" + prop + "' type='hidden' value='" + criteria[prop] + "'/>";
                            }
                        }
                        content += "</form></body></html>";
                        if (iframe[0].contentWindow.contents) {
                            iframe[0].contentWindow.contents = content;
                        } else {
                            iframe[0].contentWindow.document.open();
                            iframe[0].contentWindow.document.write(content);
                            iframe[0].contentWindow.document.close();
                        }

                        $(iframeDocument).find("form").submit();

                        var maxTimeout = 5 * 60 * 1000; //Waiting 5 minutes
                        var ticks = 0;
                        var checkTimer = setInterval(function () {
                            var lowerCaseCookie = "fileDownload=true".toLowerCase();
                            if (document.cookie.toLowerCase().indexOf(lowerCaseCookie) > -1) {
                                clearInterval(checkTimer);

                                //execute specified callback
                                getTargertContainer().stopProgressTimer();

                                //remove cookie
                                var cookieData = "fileDownload=; path=/; expires=" + new Date(0).toUTCString() + ";";
                                document.cookie = cookieData;
                                return;
                            }
                            if (ticks * 1000 > maxTimeout) {
                                clearInterval(checkTimer);
                            }
                            ticks++;
                        }, 1000);
                    }
View Code

后端准备:

public partial class ExcelBulkEditController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post), FileDownload]
        public void DownloadTemplate(GridQueryCriteriaModel criteria, MetaType metaType, bool withData)
...........
View Code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class FileDownloadAttribute : ActionFilterAttribute
    {
        public FileDownloadAttribute(string cookieName = "fileDownload", string cookiePath = "/") {
            CookieName = cookieName;
            CookiePath = cookiePath;
        }

        public string CookieName { get; set; }

        public string CookiePath { get; set; }

        /// <summary>
        /// If the current response is a FileResult (an MVC base class for files) then write a
        /// cookie to inform jquery.fileDownload that a successful file download has occured
        /// </summary>
        /// <param name="filterContext"></param>
        private void CheckAndHandleFileResult(ActionExecutedContext filterContext) {
            var httpContext = filterContext.HttpContext;
            var response = httpContext.Response;

            if ( filterContext.Result is EmptyResult )
                //jquery.fileDownload uses this cookie to determine that a file download has completed successfully
                response.AppendCookie(new HttpCookie(CookieName, "true") { Path = CookiePath });
            else
                //ensure that the cookie is removed in case someone did a file download without using jquery.fileDownload
                if ( httpContext.Request.Cookies[CookieName] != null ) {
                response.AppendCookie(new HttpCookie(CookieName, "true") { Expires = DateTime.Now.AddYears(-1), Path = CookiePath });
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext) {
            CheckAndHandleFileResult(filterContext);

            base.OnActionExecuted(filterContext);
        }
    }
View Code

 

posted @ 2017-06-13 17:24  kiddy-star  阅读(381)  评论(0编辑  收藏  举报