【发布时间】: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