【问题标题】:Web API 2 - Return Pdf, Show/Download Received Pdf File on Client (AngularJs)Web API 2 - 返回 Pdf,在客户端 (AngularJs) 上显示/下载收到的 Pdf 文件
【发布时间】:2016-04-26 15:04:04
【问题描述】:

这是我的 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? 
    });

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

【问题讨论】:

    标签: javascript c# angularjs pdf asp.net-web-api2


    【解决方案1】:

    有一个答案here 有效。与问题中的 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);
                });
        };
    

    【讨论】:

    • 根据链接的答案,您需要将 {responseType: 'arraybuffer'} 添加到 $http 调用中。否则你会收到一个空白的pdf ..
    • @RobinvanderKnaap:已经好几年了,但这段代码在生产环境中有效。
    • 我已经实现了相同的。但这仅在开发过程中有效。当我部署它时。它不起作用。显示消息:“无法加载文件”。了解更多信息。请查看:stackoverflow.com/questions/55158582/…
    【解决方案2】:

    您可以在新窗口(或标签)中打开它,而不是从角度调用 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。

    【讨论】:

    • 感谢并点赞。我贴了一个更详细的答案(本来想删q的,结果看到你回复了),我也不接受,仅供参考。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多