Redirect / show view after generated file is dowloaded

前端 未结 3 2139
予麋鹿
予麋鹿 2020-11-28 13:57

I\'ve got a controller action that downloads a dynamically generated file:

    public ActionResult DownloadFile()
    {
        var obj = new MyClass { MyStr         


        
3条回答
  •  隐瞒了意图╮
    2020-11-28 14:23

    Here is how I redirected after the file is downloaded. The main logic is to wait the redirect until the file is downloaded. To do that, a server side response is calculated and redirect is delayed using server side response time + some offset.

    Server Side Controller Code:

    [HttpPost]
    public ActionResult GetTemplate()
        {
            return Json(new {Url = Url.Action("ReturnTemplate") });
        }
    
    [HttpGet]
    public ActionResult ReturnTemplate()
        {
            FileResult fileResult = // your file path ;
            return fileResult;
        }
    

    Client Side Code:

    Javascript:

    $("#generateTemplate").click(function () {
        var startTime = (new Date()).getTime(), endTime;
    
            $.ajax({
                url: '@Url.Action("GetTemplate", "Controller")',
                type: 'POST',
                traditional: true,
                dataType: "json",
                contentType: "application/json",
                cache: false,
                data: JSON.stringify(),
                success: function (result) {
                    endTime = (new Date()).getTime();
                    var serverResponseTime = endTime - startTime + 500;
                    setInterval(function () { Back() }, serverResponseTime);
                    window.location = result.Url;
                }
            });
    });
    
    function Back() {
        window.location = '@Url.Action("Index","Controller")';
    }
    

提交回复
热议问题