Kgn-web
Kgn-web

Reputation: 7565

how to download file from server on ng-click in angular?

I have an Action which dowloads file to a local system. File can be jpeg pdf, or word.

Now when I run this action using ASP.Net, file is downloaded. But when I am calling this action on ng-click of a button. Neither I am getting any error nor file is getting downloaded.

Code Snipppet

$scope.downloadFile = function () {
    debugger;
    $http(
        {
            url: '/ControllerName/DownloadFile',
            method: 'POST',
            data: {},
            responseType: 'arraybuffer' ,
        })
    .success(function (data, status) {
        if (status == 200) {
            var file = new Blob([data], { type: 'Application/msword' });
            saveAs(file, 'test.docx');
            alert('File downloaded');

        }
    })
    .error(function () {
        alert("Error");
    })
}

In this scenaio , it is quiiet obivious that I will get an error saveAs Not defined. Hence, I included filesaver.js

Now I am not sure how to include fileSaver dependency to my controller. Because if I just include in the following way:-

app.module('myApp',['fileSaver']);

again I get error.

How to get rid of this error or if there is any other way to download file?

Note: File can be jpeg, word, pdf, zip I am using button tag

Upvotes: 3

Views: 6350

Answers (2)

Jenson Raby
Jenson Raby

Reputation: 789

Here no need to inject any angular injection, just include the file directly in your project it will work

you can include this js file for downloading

https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js

app.js

app.module('myApp',[]);

remove fileSaver from app.js

Upvotes: 0

Sariban D'Cl
Sariban D'Cl

Reputation: 2227

Angular File Saver is available. Please check hope it help

Upvotes: 2

Related Questions