使用AngularJS和WebAPI下载PDF
我有一个AngularJS应用程序,我需要调用我们的WebAPI来下载PDF文件。PDF已成功下载,但打开时为空。 我用Postman测试我的webapi代码,当我打开它时,它会给我正确的PDF。另一个值得注意的是,要下载的PDF大约为45kb,而下载的空PDF大约为77kb。 以下是我的API代码:使用AngularJS和WebAPI下载PDF,angularjs,pdf,asp.net-web-api,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/";
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)
我做错了什么?我尝试了许多不同的例子,但它们都会产生一个空的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) {
});
如果你没有选择,你可以考虑使用一些东西来排除<代码> CurATE ObjutTurl 在翻译服务器BLUB数据方面做一些事情。
$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) {
});