【问题标题】:Downloading PDF with AngularJS and WebAPI使用 AngularJS 和 WebAPI 下载 PDF
【发布时间】:2018-09-26 03:44:49
【问题描述】:

我有一个 AngularJS 应用程序,我需要调用我们的 WebAPI 来下载 PDF 文件。 PDF已成功下载,但打开时为空白。 我使用 Postman 测试了我的 webapi 代码,当我打开它时,它给了我正确的 PDF。另一个需要注意的是,要下载的 PDF 大约是 45kb,而下载的空 PDF 大约是 77kb。 这是我的 API 代码:

public IHttpActionResult GetStatement(int id)
{
    try
    {
        var path = "c:/temp/";
        var filename = "pdffile.pdf";
        var filePath = path + filename;

        if (File.Exists(filePath))
        {
            // PDF file exists
            var dataBytes = File.ReadAllBytes(filePath);
            IHttpActionResult response;
            HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
            responseMsg.Content = new ByteArrayContent(dataBytes);
            responseMsg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            responseMsg.Content.Headers.ContentDisposition.FileName = filename;
            responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            response = ResponseMessage(responseMsg);

            return response;
        }
        else
        {
            // File not found
            }

        return Ok();
    }
    catch (Exception ex)
    {
    }
}

这是我的 AngularJS 代码(我尝试使用 arraybuffer 作为 responseType,它仍然给我和空 PDF)

 $http.post('https://localhost/api/download-statement/1', { responseType: 'blob' })
    .then(function (response) {
        var binaryData = [];
        binaryData.push(response.data);

        var file = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" }));
        var a = document.createElement("a");
        a.href = file;
        a.download =  "file.pdf";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {
              document.body.removeChild(a)
        }
    },
    function (error) {

});

我做错了什么?我尝试了许多不同的示例,但它们都导致 PDF 为空。

【问题讨论】:

  • 如果您的选项不多了,您可以考虑使用 FileSaver.js 之类的东西来排除 createObjectURL 在翻译服务器 blob 数据时做一些时髦的事情。

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


【解决方案1】:

这应该可以解决问题,

  $http({
        url: 'https://localhost/api/download-statement/1',
        method: "POST",
        responseType: 'arraybuffer'
    }).success(function (data, status, headers, config) {
        var blob = new Blob([data], {type: "application/pdf"});
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }).error(function (data, status, headers, config) {
    });

【讨论】:

    猜你喜欢
    • 2017-01-24
    • 2015-11-03
    • 1970-01-01
    • 2020-06-29
    • 2017-07-27
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    相关资源
    最近更新 更多