简体   繁体   中英

Download a file using angularjs, asp.net

I'm trying to download an excel file (generated on the fly) on a button click. The functionality works fine when the code is placed server side (Reports.aspx.cs) and there is a postback on the button click. But, now, the front-end technology is Angular. So no postbacks. Tried to use the same download code in a handler and the download doesnt occur. No Save prompts, no errors. The breakpoint hits the handler.cs though.

Reports.aspx:

<button type="button" data-ng-click="DownloadExcelReport()">Download Report</button>

ReportsCtrl.js --controller

$scope.DownloadExcelReport = function () {        
        ReportsFactory.DownloadReport($scope.ReportId,$scope.SetId);       
    }

ReportsFactory.js --service

factory.DownloadReport = function (reportId, setId) {
return $http({
   url: "http://localhost:62102/download.ashx?reportId=" + reportId + "&setId=" + setId,
            method: "GET"            
        }).success(function (data, status) {
        }).error(function (data, status) {
        });
}

download.ashx.cs --handler

public void ProcessRequest(HttpContext context)
    {

        int reportId = Convert.ToInt32(context.Request.QueryString["reportId"]);
        int setId = Convert.ToInt32(context.Request.QueryString["setId"]);            
        switch (reportId)
        {
            case 1:
                DataTable dt = GetData(reportId, setId);
                if (dt != null)
                {

                    string FileName = "Responses";

                    ExportExcel obj = new ExportExcel();
                    obj.showGridLines = true;
                    obj.headerStyle = new Style(Color.SlateGray, Color.White, Color.SlateGray, ExcelBorderStyle.Thin);
                    MemoryStream ms = obj.GenerateDocument(dt);
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + ".xlsx" + "\"");
                    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();                        
                }
                break;

        }
    }

EDIT:

I have later been taught that, when using Javascript to download, the approach is different.You create a form and then submit the form with parameters. I have added the working solution.

This might help someone.

ReportsFactory.js --service

factory.DownloadReport = function (reportId, setId) {
        var form = document.createElement("form");
        form.action = "http://localhost:62102/download.asmx/DownloadReport";
        form.method = "POST";
        form.target = "_self";
        var input = document.createElement("input");
        input.type = "text";
        input.name = "params";
        input.value = reportId + "," + setId;
        form.appendChild(input);        
        form.style.display = 'none';
        document.body.appendChild(form);
        form.submit();        
    };

Using a asmx file now instead of handler.

download.asmx.cs

[WebMethod]
public void DownloadReport()
{
   string[] Params = Convert.ToString(HttpContext.Current.Request.Form["params"]).Split(',');
   string FileName = "Reports_";
   int reportId = Convert.ToInt32(Params[0]);
   int setId = Convert.ToInt32(Params[1]);
   DataTable dt = GetData(reportId,setId);
   ExportExcel obj = new ExportExcel();
   MemoryStream ms = obj.GenerateDocument(dt);
   HttpContext.Current.Response.Clear();
   HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + ".xlsx" + "\"");
   HttpContext.Current.Response.BinaryWrite(ms.ToArray());
   HttpContext.Current.Response.Flush();
   HttpContext.Current.Response.End();   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM