繁体   English   中英

带有 Web API 2 的 Angular 下载 pdf

[英]Angular download pdf with Web API 2

我们正在尝试从 web api v2 下载文件,然后使用“另存为”或在浏览器中自动下载任何解决方案都可以,但无法使任何解决方案起作用。

Chrome 中发生的事情什么都没有,什么都不做 在 IE 中,我们收到提示“您是否要允许此网站在您的计算机上打开应用程序?” 单击允许,然后什么也没有发生。

这是 WebAPI 控制器代码:

    [HttpGet]
    [Route("{pdf}/{getPDF}")]
    public async Task<IHttpActionResult> GetPDF()
    {
        var outputpath = HttpContext.Current.Server.MapPath("~/");
        HttpResponseMessage result;

        using (FileStream stream = new FileStream(outputpath + "Inv_008618_180868_33687.pdf", FileMode.Open))
        {
            result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream),                     
            };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Inv_008618_180868_33687.pdf",
                Size = stream.Length
            };

            return Ok(result);

        }
    }

我认为上面的代码是正确的,但不是 100% 确定,因为文件大小非常小。

这是角代码:

getPDF: function () {
            var scope = this;
            var urlApi = 'http://localhost:59242/supplier/pdf/';

            return $http({
                url: urlApi,
                responseType: 'arraybuffer'
            }).then(function (response) {
                    var file = new Blob([response], { type: 'application/pdf' });                        
                    var fileURL = URL.createObjectURL(file);

                    var pdf = $sce.trustAsResourceUrl(fileURL);

                    //var element = angular.element('<a/>');
                    //element.attr({
                    //    href: 'data:attachment/pdf;charset=utf-8,' + encodeURI(response),
                    //    target: '_self',
                    //    download: 'test.pdf'
                    //})[0].click();

                    window.open(pdf);
              }

                            return response.data;
                        })
                        .catch(function (err) {
                        })
        }

我要感谢您的回复

使用 ngFileSaver 解决了这个问题,谢谢

暂无
暂无

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

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