无法使用AngularJS在新标签中打开PDF

时间:2019-02-25 22:59:57

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

我正在尝试使用AngularJS在新选项卡中打开PDF文档。像这样从.NET Web API控制器将PDF作为字节数组加载:

[HttpPost]
[Route("PdfDocument")]
public async Task<HttpResponseMessage> GetPdf(int it)
{
    MemoryStream memoryStream = new MemoryStream();
    PdfService pdfService = new PdfService();

    using (var stream = await pdfService.GetDocument(id))
    {
        try
        {
            stream.CopyTo(memoryStream);

            stream.Close();
        }
        catch(Exception ex)
        {
            stream.Close();
            throw new Exception("Exception: ", ex);
        }
    }

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(memoryStream.ToArray());
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
    {
        FileName = "file.pdf"
    };

    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

    return response;
}

在用于加载PDF文档的PdfService类中,我具有以下方法:

public async Task<Stream> GetDocument(int id)
{
    try
    {
        var stream = await this.getPdfDocument(id);

        return stream;
    }
    catch (Exception ex)
    {
        throw new Exception("Exception: ", ex);
    }
}

private async Task<Stream> getPdfDocument(int id)
{
    try
    {
        var credentials = new CredentialsCache();
        credentials.Add(....);

        using (var handler = new HttpClientHandler() { Credentials = credentialCache })
        {
            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.ExpectContinue = true;

                var stream = await client.GetStreamAsync(id);

                return stream;
            }
        }    
    }
    catch (Exception ex)
    {
        throw new Exception("Exception: ", ex);
    }
}

在客户端,用于加载PDF字节数组并将其显示在新的浏览器选项卡中的代码如下(这在AngularJS指令中):

scope.openPdfInTab = function() {
    var pdfId = 1234;

    scope.pdfParameters = {
        "id": pdfId
    }

    resource.pdf.open(scope.pdfParameters,
        function(data) {
            var file = new Blob([data.content], { type: "application/pdf" });
            var fileURL = URL.createObjectURL(file);

            window.open(file, '_blank');
        }
    );
}

问题是什么也没发生。新标签页没有打开,开发人员控制台(在Chrome中)没有任何错误,如果我对其进行调试,可以看到从Web API返回的有效数据看起来像什么。屏幕快照1是Web API控制器中响应的外观,屏幕截图2包含客户端的PDF数据,文件和文件URL。

屏幕截图1

Screenshot 1

截屏2

Screenshot 2

在客户端代码中,我尝试在下面的行中用“ data”替换“ data.content”,结果相同:

var file = new Blob([data.content], { type: "application/pdf" });

你知道这里出了什么问题吗?

0 个答案:

没有答案