简体   繁体   English

如何在ng-click中从服务器下载文件?

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

I have an Action which dowloads file to a local system. 我有一个Action文件将文件下载到本地系统。 File can be jpeg pdf, or word. 文件可以是jpeg pdf,也可以是单词。

Now when I run this action using ASP.Net, file is downloaded. 现在,当我使用ASP.Net运行此操作时,将下载文件。 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 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. 在这个scenaio中,我会得到一个错误,因为我没有定义错误。 Hence, I included filesaver.js 因此,我包括filesaver.js

Now I am not sure how to include fileSaver dependency to my controller. 现在我不确定如何将fileSaver依赖项包含到我的控制器中。 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 注意:文件可以是jpeg,word,pdf,zip我正在使用按钮标签

Angular File Saver is available. Angular File Saver可用。 Please check hope it help 请检查希望它有所帮助

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 你可以包含这个js文件进行下载

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

app.js app.js

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

remove fileSaver from app.js 从app.js中删除fileSaver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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