简体   繁体   English

AngularJS 从 ASP.NET MVC 控制器保存文件

[英]AngularJS Save File From ASP.NET MVC Controller

I am returning a file from an ASP.NET MVC controller and I want to download it as an attachment using AngularJS.我正在从 ASP.NET MVC 控制器返回一个文件,我想使用 AngularJS 作为附件下载它。

MVC Controller: MVC控制器:

return File(renderedBytes, mimeType);

AngularJS: AngularJS:

function generatePDF(reportRequest) {

            var reportController = "Report";
            var controllerUrl = ngAppSettings.homeBaseUri + reportController + "/GeneratePDF";
            var deferred = $q.defer();
            $http({
                method: "POST",
                url: controllerUrl,
                data: reportRequest
            }).success(function (data, status, headers, cfg) {
                //window.open(controllerUrl, "_self", "");
                deferred.resolve(data);
            }).error(function (err, status) {
                deferred.reject(err);
            });

            return deferred.promise;

        };

I've tried various ways as suggested on the similar questions about this but I'm not getting it.我已经按照类似问题的建议尝试了各种方法,但我没有得到它。

I've tried this too.我也试过这个

My breakpoints hit without any problems inside the GeneratePDF controller but nothing happens after that.我的断点在 GeneratePDF 控制器内部没有任何问题,但之后没有任何反应。 How would I go about this?我该怎么办?

EDIT:编辑:

I also tried angular file saver but I'm getting an error that the format should be in BLOB.我也尝试过angular 文件保护程序,但我收到一个错误,格式应该是 BLOB。 If I can only convert the response to a blob then I think this might be it.如果我只能将响应转换为 blob,那么我认为可能就是这样。

TIA TIA

If your C# Controller endpoint returns a FileContentResult (which it appears that it does), then you shouldn't need to worry about promises.如果您的 C# 控制器端点返回 FileContentResult(看起来确实如此),那么您无需担心承诺。 You can simply do the following...您可以简单地执行以下操作...

function generatePDF(reportRequest) {
            var reportController = "Report";
            var controllerUrl = ngAppSettings.homeBaseUri + reportController + "/GeneratePDF";
            window.open(controllerUrl, "_blank");
        };

I am doing this in one of my apps and it is working as expected.我正在我的一个应用程序中执行此操作,并且它按预期工作。 Is there a particular reason you were using the $q service to return a promise?您使用 $q 服务返回承诺是否有特殊原因?

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

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