使用 AngularJS 和 WebAPI 下载 PDF



我有一个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 代码(我已经尝试了一个数组缓冲区作为响应类型,它仍然给我和空的 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。

应该可以解决问题,

$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) {
});

最新更新