Efficient File Download Implementation Using AngularJS and ASP.NET Web API

Nov 27, 2025 · Programming · 8 views · 7.8

Keywords: AngularJS | ASP.NET Web API | File Download | Blob | ArrayBuffer

Abstract: This technical article provides a comprehensive guide on implementing file downloads in AngularJS applications that interact with ASP.NET Web API. It details two primary methods: a simple approach using window.open for broad compatibility, and an advanced AJAX-based method utilizing arraybuffer and blob for binary file handling. The article includes rewritten code examples, explanations of Web API configuration, and browser compatibility considerations to ensure robust implementation.

Introduction

In modern web applications, downloading files from a server is a common requirement. This article addresses how to implement file downloads in an AngularJS frontend that communicates with an ASP.NET Web API backend. The challenge lies in handling binary data and triggering the download in the browser.

Simple Download Method

A straightforward way to download a file is by using the window.open method in JavaScript. This approach bypasses the need for complex AJAX handling and works across all browsers.

function downloadFile(downloadPath) {
    window.open(downloadPath, '_blank', '');
}

In this method, the anchor tag can directly call this function, which opens the file URL in a new window or tab, triggering the browser's download behavior if the server sets appropriate headers.

Ajax Binary Download Method

For more control over the download process, such as handling binary data or custom headers, an AJAX-based approach is preferred. This involves using AngularJS's $http service with a response type of arraybuffer.

First, configure the Web API to return the file with proper headers:

[Authorize]
[Route("getfile")]
public HttpResponseMessage GetTestFile()
{
    // Code to check file existence
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");
    if (!File.Exists(localFilePath))
    {
        return Request.CreateResponse(HttpStatusCode.Gone);
    }
    else
    {
        var result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SampleImg";
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Headers.Add("X-Filename", "SampleImg.jpg");
        return result;
    }
}

In AngularJS, handle the response:

$scope.downloadFile = function(httpPath) {
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success(function(data, status, headers) {
        var filename = headers('x-filename') || 'download.bin';
        var contentType = headers('content-type') || 'application/octet-stream';
        var blob = new Blob([data], { type: contentType });
        
        if (navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, filename);
        } else if (navigator.webkitSaveBlob) {
            navigator.webkitSaveBlob(blob, filename);
        } else if (navigator.mozSaveBlob) {
            navigator.mozSaveBlob(blob, filename);
        } else {
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if (urlCreator) {
                var url = urlCreator.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = url;
                link.download = filename;
                document.body.appendChild(link); // Required for some browsers
                link.click();
                document.body.removeChild(link);
                urlCreator.revokeObjectURL(url);
            } else {
                window.open(httpPath, '_blank', ''); // Fallback
            }
        }
    })
    .error(function(data, status) {
        console.error("Download failed with status: " + status);
    });
};

This code attempts to use the most efficient method available in the browser, with fallbacks for compatibility. Note that in some browsers, appending the link to the body is necessary for the click event to work.

Browser Compatibility

Different browsers support various methods for saving blobs. Internet Explorer has msSaveBlob, while WebKit-based browsers like Chrome and Safari may support webkitSaveBlob, and Firefox has mozSaveBlob. The download attribute in anchor tags is widely supported but may require the link to be in the DOM. The provided code includes checks and fallbacks to ensure wide compatibility.

Conclusion

Implementing file downloads in AngularJS with ASP.NET Web API can be achieved through simple or advanced methods. The choice depends on the required level of control and browser support. By setting proper headers in the Web API and handling the response appropriately in AngularJS, developers can ensure a seamless download experience for users. Always test in target browsers to verify compatibility.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.