Web API 2 - 返回 pdf,在客户端 (AngularJs) 上显示/下载收到的 pdf 文件
Web API 2 - Return Pdf, Show/Download Received Pdf File on Client (AngularJs)
这是我的 Web API 2 控制器中的代码:
//pdfBytes is a valid set of...pdfBytes, how it's generated is irrelevant
Byte[] pdfBytes = pdfConverter.GeneratePdf(myPdfString);
//using HttpResponseMessage instead of IHttpActionResult here because I read
//that the latter can cause problems in this scenario
var response = new HttpResponseMessage();
//Set reponse content to my PDF bytes
response.Content = new ByteArrayContent(pdfBytes);
//Specify content type as PDF - not sure if this is necessary
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
如何在客户端上收到 PDF 后触发浏览器自动下载 PDF 或在新窗口中打开它?(注意 - 我不确定字节数组是否是我想在这里接收的格式)。
callToGetPdfFromDb()
.success(function (pdfFromWebApi) {
console.log('Got pdf...'');
//How do I show the received PDF to the user?
});
我对任何类型的文件下载/上传都很陌生,所以如果我缺少一些非常基本的东西,我深表歉意。我对正确方向的指针作为回应感到非常满意。
这里有一个有效的答案。与问题中的 C# 代码一起使用的完整调用/响应。请注意,我留下这个问题是因为我认为它比现有的问题更具体一些,而且我很难找到答案:
$scope.getPdf= function(){
var pdfReportUrl = yourBaseUrl+ '/generatepdf';
var runDbCallToGetPdf = function(){
return $http({
method: 'GET',
url: pdfReportUrl,
responseType:'arraybuffer'
});
};
runDbCallToGetPdf ()
.success(function (pdfBytes) {
var pdfFile = new Blob([pdfBytes], {type: 'application/pdf'});
var pdfFileUrl = URL.createObjectURL(pdfFile );
window.open(pdfFileUrl);
});
};
无需从角度调用 Web API 端点,只需在新窗口(或选项卡)中打开它即可。
var getUrl = //path to web api endpoint to get generated pdf
// make sure to inject $window service
$window.open(getUrl, "_blank");
如果响应的 MIME 类型设置正确,浏览器应该能够打开 pdf。
相关文章:
- 如何使用javascript或html下载PDF格式的填写表单
- 在提交时打开thankyou.html+下载PDF
- 如何在不在本地下载的情况下将url中提供的文件(pdf/doc)转换为json/string/base64格式
- 下载HTML5/Javascript MOBILE应用程序中的PDF文件
- 下载所选语言的pdf文件
- CSV、PDF、Excel文件在dataTables的导出扩展中作为blob下载
- 如何在网络上下载pdf
- 使用window.print内容以pdf格式下载网页
- 将数据库中的数据转换为可下载的PDF文件
- 如何使用HtmlUnit下载PDF文件
- 如何使用JQuery禁用pdf文件下载选项
- 使用javascript压缩并下载多个PDF文档
- 如何创建和下载PDF和docx格式的文件,该文件将从AngularJS中的表中的数据创建
- 下载pdf格式不正确
- 将屏幕截图显示为pdf下载链接
- 如何通过ajax调用将pdf下载到nodejs服务器
- jsPDF输出PDF下载
- 自动为PDF下载添加唯一编号
- 当点击按钮时,强制PDF下载
- Laravel快速推送PDF下载