Web API 2 - 返回 pdf,在客户端 (AngularJs) 上显示/下载收到的 pdf 文件

Web API 2 - Return Pdf, Show/Download Received Pdf File on Client (AngularJs)

本文关键字:pdf 下载 显示 文件 API 返回 Web 客户端 AngularJs      更新时间:2023-09-26

这是我的 Web API 2 控制器中的代码:

//pdfBytes is a valid set of...pdfBytes, how it's generated is irrelevant
Byte[] pdfBytes = pdfConverter.GeneratePdf(myPdfString);
//using HttpResponseMessage instead of IHttpActionResult here because I read
//that the latter can cause problems in this scenario
var response = new HttpResponseMessage();
//Set reponse content to my PDF bytes
response.Content = new ByteArrayContent(pdfBytes);
//Specify content type as PDF - not sure if this is necessary
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;

如何在客户端上收到 PDF 后触发浏览器自动下载 PDF 或在新窗口中打开它?(注意 - 我不确定字节数组是否是我想在这里接收的格式)。

callToGetPdfFromDb()
    .success(function (pdfFromWebApi) {
        console.log('Got pdf...'');
        //How do I show the received PDF to the user? 
    });

我对任何类型的文件下载/上传都很陌生,所以如果我缺少一些非常基本的东西,我深表歉意。我对正确方向的指针作为回应感到非常满意。

这里有一个有效的答案。与问题中的 C# 代码一起使用的完整调用/响应。请注意,我留下这个问题是因为我认为它比现有的问题更具体一些,而且我很难找到答案:

    $scope.getPdf= function(){
        var pdfReportUrl = yourBaseUrl+ '/generatepdf';
        var runDbCallToGetPdf =  function(){
            return $http({
                method: 'GET',
                url: pdfReportUrl,
                responseType:'arraybuffer'
            });
        };
        runDbCallToGetPdf ()
            .success(function (pdfBytes) {
                var pdfFile = new Blob([pdfBytes], {type: 'application/pdf'});
                var pdfFileUrl = URL.createObjectURL(pdfFile );
                window.open(pdfFileUrl);
            });
    };

无需从角度调用 Web API 端点,只需在新窗口(或选项卡)中打开它即可。

var getUrl = //path to web api endpoint to get generated pdf
// make sure to inject $window service
$window.open(getUrl, "_blank");

如果响应的 MIME 类型设置正确,浏览器应该能够打开 pdf。