首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ajax在MVC中导出

使用ajax在MVC中导出
EN

Stack Overflow用户
提问于 2016-03-29 23:50:32
回答 1查看 1.9K关注 0票数 1

我正在尝试通过ajax导出在我的控制器中创建的zip文件。我看了几个相关的问题,但它们都略有不同,我无法将它们联系起来。有时,我什么也得不到。其他时候,我的ajax转到窗口位置,所有东西都崩溃了。

我的ajax调用:

代码语言:javascript
复制
$.ajax({
     url: "/Somewhere/Export",
     type: "POST",
     dataType: 'html',
     data: {
         jsonModel: JSON.stringify(modelData),
         fileType: $("#toggle-2").val()
      },
      success: function (returnValue) {
           window.location = '/Somewhere/Export/Download?file=' + returnValue;
      },
});

一次尝试我的控制器剪辑。:

代码语言:javascript
复制
[HttpPost, Authorize]
public ActionResult Export(string jsonModel, int? fileType)
{
    MemoryStream workingStream = GenerateExportFile(jsonModel, fileType);
    return File(workingStream, "application/zip", folderName + ".zip");
}

我也尝试过使用响应流:

代码语言:javascript
复制
[HttpPost, Authorize]
public ActionResult Export(string jsonModel, int? fileType)
{
    MemoryStream workingStream = GenerateExportFile(jsonModel, fileType);
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + folderName + ".zip");
    Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Zip;
    workingStream.WriteTo(Response.OutputStream);
    Response.End();
    return RedirectToAction("Index");
}

我看过的内容:Generating excel then downloadingDownload excel via ajax mvcDownloading zip through asp mvc

EN

回答 1

Stack Overflow用户

发布于 2016-03-30 00:41:28

在javascript中(使用blockui和jquery-file-download插件):

代码语言:javascript
复制
        $(window).block();
        $.fileDownload('Export', {
            httpMethod: 'POST',
            data: inputs,
            successCallback: function (url) {
                $(window).unblock();
            },
            failCallback: function (responseHtml, url) {
                $(window).unblock();
                $(window).html(url + '</br>' + responseHtml);
            }
        });

在控制器中(发送文件和设置cookie):

代码语言:javascript
复制
    public ActionResult Export()
    {
        var e = new ExportZip();
        var request = Request.Unvalidated;
        byte[] data = e.Create(request.Form);

        Response.SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });
        return File(data, "application/zip", "file.zip");
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36289120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档