做一些处理并下载文件.NET MVC

时间:2017-07-08 14:41:27

标签: asp.net-mvc asynchronous task

我想创建一个excel,保存并下载它。但是在创建excel文件时,我希望用户应该执行不同的过程。这是我的控制器动作:

[HttpGet]
    public async Task<ActionResult> CreateExcel() {

        var path = string.Empty;

        await Task.Factory.StartNew(() => {
            path = SaveExcel();
        });

        return File(System.IO.File.ReadAllBytes($"{path}.xls"),
            System.Net.Mime.MediaTypeNames.Application.Octet,$"{Guid.NewGuid()}.xls");

    }

private string SaveExcel() {
        //this method will create an excel File and will return the file's path.
    }

但是当我跳转到另一个URL时,下载正在取消。

1 个答案:

答案 0 :(得分:0)

您不能像这样平行您的应用程序。如果你想允许用户做其他事情,而Excel正在生成,我想以这种方式建议你。

打开新的弹出窗口,其中包含“请等待,您的Excel正在生成”文本,然后在此弹出窗口中,您可以对控制器操作进行GET调用。同时,用户可以在主窗口中浏览网站

 <a id="generateExcel">Generate excel for me</a>

<script>
    $(document).ready(function(){
        $('#generateExcel').click(function() {
            var url = '{LINK_TO_YOUR_CREATE_EXCEL_URL}';
            var newWindow = window.open('', 'popUpWindow', 'height=500,width=500,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes');
            newWindow.document.write("<html><head></head><body>Please wait, your excel is generating<script>window.location='"+url+"'</script></body></html>");
            newWindow.document.close();
            return false;
        })
    })  
</script>