Download Excel file via AJAX MVC

后端 未结 14 1766
说谎
说谎 2020-11-22 02:30

I have a large(ish) form in MVC.

I need to be able to generate an excel file containing data from a subset of that form.

The tricky bit is that this shouldn

14条回答
  •  旧巷少年郎
    2020-11-22 03:01

    This thread helped me create my own solution that I will share here. I was using a GET ajax request at first without issues but it got to a point where the request URL length was exceeded so I had to swith to a POST.

    The javascript uses JQuery file download plugin and consists of 2 succeeding calls. One POST (To send params) and one GET to retreive the file.

     function download(result) {
            $.fileDownload(uri + "?guid=" + result,
            {
                successCallback: onSuccess.bind(this),
                failCallback: onFail.bind(this)
            });
        }
    
        var uri = BASE_EXPORT_METADATA_URL;
        var data = createExportationData.call(this);
    
        $.ajax({
            url: uri,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: download.bind(this),
            fail: onFail.bind(this)
        });
    

    Server side

        [HttpPost]
        public string MassExportDocuments(MassExportDocumentsInput input)
        {
            // Save query for file download use
            var guid = Guid.NewGuid();
            HttpContext.Current.Cache.Insert(guid.ToString(), input, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
            return guid.ToString();
        }
    
       [HttpGet]
        public async Task MassExportDocuments([FromUri] Guid guid)
        {
            //Get params from cache, generate and return
            var model = (MassExportDocumentsInput)HttpContext.Current.Cache[guid.ToString()];
              ..... // Document generation
    
            // to determine when file is downloaded
            HttpContext.Current
                       .Response
                       .SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });
    
            return FileResult(memoryStream, "documents.zip", "application/zip");
        }
    

提交回复
热议问题