使用AngularJS和WebAPI下载PDF

时间:2018-09-26 03:44:49

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

我有一个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为空。

1 个答案:

答案 0 :(得分: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) {
    });