在使用Angular和Spring Boot进行Excel文件保存时,第一次保存成功,但第二次保存时会出现'Response is not a Blob”错误。这是因为第一次成功保存后,返回的响应对象会被销毁,第二次保存时会尝试访问不存在的对象,导致错误。为了解决这个问题,可以使用ngx-toastr库来显示错误信息,并在每次保存后,手动更新响应对象。
这里给出一个示例代码:
在Angular中:
export class AppComponent { title = 'excel-app'; private baseUrl = 'http://localhost:8080/api/excel'; fileUrl;
constructor(private http: HttpClient, private toastr: ToastrService) { }
downloadFile() { this.http.get(this.baseUrl + '/download', { responseType: 'blob' }) .subscribe(res => { const url = window.URL.createObjectURL(res); window.open(url); }); }
uploadFile(event) { const file = event.target.files[0]; const formData = new FormData(); formData.append('file', file);
this.http.post(this.baseUrl + '/upload', formData).subscribe(
(res) => {
this.fileUrl = res.fileUrl;
this.toastr.success('File uploaded successfully!');
},
(error) => {
this.toastr.error(error.message);
}
);
}
saveFile() { this.http.get(this.baseUrl + '/save', { responseType: 'blob' }) .subscribe(res => { const url = window.URL.createObjectURL(res); const a = document.createElement('a'); document.body.appendChild(a); a.setAttribute('style', 'display: none'); a.href = url; a.download = 'report.xlsx'; a.click(); window.URL.revokeObjectURL(url); }, error => { this.toastr.error(error.message); }); // Manually update response object this.http.get(this.baseUrl + '/save') .subscribe(res => { console.log(res); }); } }
在Spring Boot中:
@RestController @RequestMapping("/api/excel")