Typescript调用AJAX Post下载PDF类型转换报错解决方案咨询
问题根因
你的接口声明返回类型是IHttpActionResult,但直接返回自定义的TemplateFileDto对象,二者类型不匹配,所以触发转换报错。同时前后端都缺少二进制文件传输的必要配置,就算类型匹配也会出现PDF损坏无法打开的问题。
可行解决方案
1. 后端接口修改
构造标准二进制文件响应即可,修改后的Controller代码如下:
using System.Net; using System.Net.Http; using System.Net.Http.Headers; [HttpGet, HttpPost] [ApplicationApiAuthorize("Administrator, ContentManager")] public IHttpActionResult PrintTemplates([FromBody] List<string> versionKeys) { var templates = versionKeys .Select(v => TemplatesDataService.GetTemplate(v)) .ToList(); var templateIds = templates.Select(b => b.Id).ToList(); var templateFile = TemplatesDataService.PrintTemplate(templateIds); if (templateFile == null) return NotFound(); // 构造文件响应对象 var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(templateFile.Content) }; // 设置文件类型头 response.Content.Headers.ContentType = new MediaTypeHeaderValue(templateFile.ContentType ?? "application/pdf"); // 配置文件行为:inline为浏览器预览,attachment为直接触发下载,可自定义文件名 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline") { FileName = templateFile.FileName }; // 用ResponseMessage包裹返回,符合IHttpActionResult接口要求 return ResponseMessage(response); }
2. 前端代码修改
必须给AJAX请求添加responseType: 'blob'配置,否则默认会把二进制数据解析为字符串导致PDF损坏:
printItems(versionKeys: string[]): JQueryPromise<any> { console.log('printItems'); $.ajax({ type: "post", contentType: "application/json", data: JSON.stringify(versionKeys), url: this.apiUrls.PrintTemplates, responseType: 'blob', // 新增此行,指定响应类型为二进制 success: function (data, status, xhr) { var file = new Blob([data], { type: 'application/pdf' }); var fileURL = URL.createObjectURL(file); window.open(fileURL); // 可选:10秒后释放内存 setTimeout(() => URL.revokeObjectURL(fileURL), 10000); console.log('success'); } }); return; }
如果出现浏览器拦截弹窗的问题,可以替换window.open逻辑为a标签模拟点击下载:
const aTag = document.createElement('a'); aTag.href = fileURL; aTag.download = '打印模板.pdf'; document.body.appendChild(aTag); aTag.click(); document.body.removeChild(aTag);
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

