Angular端下载Spring Boot服务端生成的PDF文件报JSON解析错误如何解决
Angular前端调用后端接口下载PDF触发JSON解析错误问题
问题背景
- 核心开发目标:实现Angular前端发起请求,下载由Spring Boot服务端生成的PDF文件
- 已验证正常的调用链路:
- 直接通过浏览器地址栏访问目标API,可正常触发PDF文件下载
- 使用Postman调用同一接口,可正常返回PDF格式的响应内容,无报错
- 异常触发场景:从前端UI页面发起接口请求时,控制台抛出解析错误,无法获取PDF文件流
- 排查观测:已实际核对接口返回、请求头配置环节,后端接口响应内容正常,前端请求携带的授权头、内容类型配置均符合预期
异常报错详情
控制台抛出的完整报错信息如下:
SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad message: "Unexpected token % in JSON at position 0" stack: "SyntaxError: Unexpected token % in JSON at position 0↵ at JSON.parse ()↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19662:51)↵"
报错本质:Angular HttpClient默认按JSON格式解析响应体,而PDF二进制流的固定开头为%PDF,解析到首个%字符时直接触发JSON语法解析失败
现有实现代码
后端接口代码
Controller层
@RequestMapping(value = "/downloadPDF/", method = RequestMethod.GET, produces = "application/pdf") public ResponseEntity<Resource> downloadServicePack(@RequestHeader("Authorization") String token, HttpServletRequest request) throws WorkflowException, Exception { String fileName = "TWEVL_ServiceDesignPack.pdf"; Resource resource = fileStorageService.loadFileAsResource(fileName); // 尝试获取文件的内容类型 String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) { } // 若无法确定内容类型则使用默认的内容类型 if (contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); }
Service层
@Service public class FileStorageService { private final Path fileStorageLocation; @Autowired public FileStorageService(FileStorageProperties fileStorageProperties) throws Exception { this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()) .toAbsolutePath().normalize(); try { Files.createDirectories(this.fileStorageLocation); } catch (Exception ex) { throw new Exception("无法创建存储上传文件的目录。", ex); } } public Resource loadFileAsResource(String fileName) throws Exception { try { Path filePath = this.fileStorageLocation.resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if(resource.exists()) { return resource; } else { throw new Exception("未找到文件:" + fileName); } } catch (Exception ex) { throw new Exception("未找到文件:" + fileName, ex); } } }
前端实现代码
JWT拦截器配置
@Injectable() export class JwtInterceptor implements HttpInterceptor { constructor(private authenticationService: AuthenticationService) {} intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { // 若存在有效令牌则在请求头中添加JWT授权信息 const token = this.authenticationService.currentUserValue; request = request.clone({ setHeaders: { Authorization: `Bearer ${token.token}`, Accept: `application/pdf`, responseType:'blob', 'Content-Type':`application/pdf` } }); return next.handle(request); } }
页面端下载逻辑
downloadServicePackPDF() { this.tcmtSrv .downloadServicePack() .subscribe( (blob: Blob) => { console.log('report is downloaded'); }, (error) => { console.log(error); } ); }
通用服务方法封装
downloadServicePack() { // 请求头由Interceptor统一处理 return this.apiSrv.get(DOWNLOAD_SERVICE_PACK,''); }
问题原因与修正方案
核心问题原因
- 配置位置错误:拦截器中将
responseType: 'blob'写入了setHeaders对象中,而responseType是HttpRequest实例的独立配置项,并非请求头字段,该配置不会生效,导致Angular默认使用JSON格式解析响应内容 - 通用方法未适配二进制流:封装的通用
get方法默认按JSON格式接收响应,没有针对PDF下载的请求单独指定Blob格式的响应类型
修正操作
- 调整JWT拦截器的请求克隆逻辑,将
responseType从请求头配置中移出,和setHeaders同级放置:request = request.clone({ setHeaders: { Authorization: `Bearer ${token.token}`, Accept: `application/pdf`, 'Content-Type':`application/pdf` }, responseType: 'blob' // 配置放在实例同级,而非请求头内 }); - 在通用API服务的
get方法中,针对文件下载类请求单独传入响应类型配置,无需完全依赖拦截器统一处理:downloadServicePack() { return this.httpClient.get(DOWNLOAD_SERVICE_PACK, { responseType: 'blob', headers: { Accept: 'application/pdf' } }); } - 拿到Blob响应后,补充触发浏览器下载的逻辑,避免仅拿到流却不触发文件保存:
downloadServicePackPDF() { this.tcmtSrv .downloadServicePack() .subscribe( (blob: Blob) => { const downloadUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = 'TWEVL_ServiceDesignPack.pdf'; link.click(); window.URL.revokeObjectURL(downloadUrl); }, (error) => { console.log('下载失败', error); } ); }
内容的提问来源于stack exchange,提问作者Pinki Sharma
相关产品推荐
相关产品推荐

