Angular对接SpringBoot下载文件报JSON解析错误如何解决
Angular下载Spring Boot文件报JSON解析错误修复方案
错误根因
Angular服务层发起文件下载请求时,错误将responseType设置为json,但Spring Boot接口实际返回的是二进制文件流。Angular收到响应后会默认调用JSON.parse解析响应内容,二进制文件的文件头标识(比如PNG格式开头的特殊字符�)不属于合法JSON字符,直接触发解析报错。
具体修复步骤
1. 修正Angular服务层请求配置
将响应类型从json改为blob,告知Angular当前请求返回二进制数据,不要执行JSON解析逻辑:
public downProduct(fileUrl: string | undefined): Observable<Blob>{ return this.httpClient.get(this.urlBack+"products/download/"+fileUrl, { responseType: 'blob' // *核心修改项:指定响应为二进制Blob格式 }); }
2. 调整组件层下载处理逻辑
原逻辑直接取response.url的方式不适用于Blob类型响应,需要基于返回的二进制数据创建临时可访问URL,再执行预览或下载操作:
downloadProduct(fileUrl){ this.httpClientService.downProduct(fileUrl).subscribe((response: Blob) => { // 生成Blob临时访问地址 const blobUrl = window.URL.createObjectURL(response); // 新开窗口预览文件 window.open(blobUrl, '_blank'); // 若需要直接触发下载而非预览,替换为以下逻辑即可 // const downloadLink = document.createElement('a'); // downloadLink.href = blobUrl; // downloadLink.download = fileUrl; // downloadLink.click(); // 释放临时URL占用的内存 // window.URL.revokeObjectURL(blobUrl); }) }
3. (可选规范优化)Spring Boot响应头调整
原有Content-Disposition响应头写法不符合HTTP标准,建议调整为规范格式,避免部分浏览器出现文件名识别异常:
@CrossOrigin(origins = "http://localhost:4200") @GetMapping("download/{filename}") public ResponseEntity<Resource> downloadFiles(@PathVariable("filename") String filename) throws IOException { Path filePath = Paths.get(DIRECTORY).toAbsolutePath().normalize().resolve(filename); if(!Files.exists(filePath)) { throw new FileNotFoundException(filename + " was not found on the server"); } Resource resource = new UrlResource(filePath.toUri()); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("File-Name", filename); // 按HTTP标准规范书写Content-Disposition头,filename属性值加双引号 httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\""); return ResponseEntity.ok() .contentType(MediaType.parseMediaType(Files.probeContentType(filePath))) .headers(httpHeaders) .body(resource); }
修改完成后重启前后端服务,重新触发下载即可正常获取文件,不会再出现JSON解析错误。
内容的提问来源于stack exchange,提问作者BOUABDELLAH SAID ABDELDJALIL
相关产品推荐
相关产品推荐

