如何使用ajax window.location下载文件 [英] How to download a file with ajax window.location

查看:887
本文介绍了如何使用ajax window.location下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用于过滤数据表的页面上有过滤器.

I have filters on a page that filters the data tables.

还有一个独立的按钮,可以将数据导出为ex​​cel.

And an independent button to export data as excel.

我已遵循以下示例:通过AJAX MVC下载Excel文件

单击导出按钮时,jQuery将读取所有过滤器值,并将结果传递回服务器,如下所示:

When the export button is clicked jQuery reads all the filter values and pass the result back to server as below:

 $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: filterData
    }).done(function (returnData) {
        if (returnData.success) {
            window.location = returnData.locationUrl;        
        }      
    });

在服务器上,我有2个操作

On the server I have 2 actions

    [HttpPost]
    public ActionResult ExportTo(SearchVm searchVm)
    {

        var data = _service.GetSearchTerm(searchVm).Take(150).ToList();

        string handle = Guid.NewGuid().ToString();
        TempData[handle] = data;
        var fileName = $"C-{handle}.xlsx";
        var locationUrl = Url.Action("Download", new { fileGuid = handle, fileName });

        var downloadUrl = Url.Action("Download");
        return Json(new { success = true, locationUrl, guid = handle, downloadUrl }, JsonRequestBehavior.AllowGet);

    }

    [HttpGet]
    public ActionResult Download(string fileGuid, string fileName)
    {
        if (TempData[fileGuid] != null)
        {
            var fileNameSafe = $"C-{fileGuid}.xlsx";
            var data = TempData[fileGuid] as List<Company>;

            using (MemoryStream ms = new MemoryStream())
            {
                GridViewExtension.WriteXlsx(GetGridSettings(fileNameSafe), data, ms);
                MVCxSpreadsheet mySpreadsheet = new MVCxSpreadsheet();
                ms.Position = 0;
                mySpreadsheet.Open("myDoc", DocumentFormat.Xlsx, () =>
                {
                    return ms;
                });
                byte[] result = mySpreadsheet.SaveCopy(DocumentFormat.Xlsx);
                DocumentManager.CloseDocument("myDoc");
                Response.Clear();
                Response.ContentType = "application/force-download";
                Response.AddHeader("content-disposition", $"attachment; filename={fileNameSafe}");
                Response.BinaryWrite(result);
                Response.End();
            }
           }
            return new EmptyResult();
        }

上面的代码可以很好地在本地计算机上下载文件.但是,当我将其置于服务器上时,单击导出"按钮会将用户定向到URL,而不是下载文件.

The code above works fine to download files on local machine. However, When I make it live on the server, Export button click directs the user to the URL instead of downloading the file.

我不知道为什么会这样.该应用程序托管在azure Web服务上.我可以看到本地和生产之间的唯一区别是生产具有ssl.

I cannot figure out why this is happening. The App is hosted on the azure web service. The only difference I can see between local and production is that production has ssl.

window.location是否有任何限制?为什么它会迫使浏览器在本地计算机上下载文件,却会重定向用户以链接到生产环境?

Is there any limitation with window.location? Why it would force browser to download file on local machine but it would redirect user to link on the production?

我已经检查了chrome控制台,没有错误.

I have checked chrome console and there is no error.

知道为什么吗?

谢谢

推荐答案

-将fileName和fileGuid返回到您的Ajax方法并连接操作URL,而不是在后端创建它,然后调用下载操作.

-Return the fileName and the fileGuid to your Ajax method and concatenating the action URL instead of creating it in the backend and then call download action.

-更改返回的数据:

    [HttpPost]
    public ActionResult ExportTo(SearchVm searchVm)
    {
        var data = _service.GetSearchTerm(searchVm).Take(150).ToList();
        var handle = Guid.NewGuid().ToString();
        TempData[handle] = data;
        var fileName = $"C-{handle}.xlsx";
       /// var locationUrl = Url.Action("Download", new { fileGuid = handle, fileName });
      //  var downloadUrl = Url.Action("Download");
        return Json(new { success = true, guid = handle, fileName=fileName }, JsonRequestBehavior.AllowGet);
    }

-更改ajax完成的功能:

-Change ajax done function :

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: filterData
}).done(function (returnData) {
        if (returnData.success)
        {
            window.open('/download/' +returnData.guid + '/' + returnData.fileName, '_blank', '');
        }
    });

这篇关于如何使用ajax window.location下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆