I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code:
Angular service:
getZip(fileName: string) : Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/zip',
'Accept': 'application/zip'
}),
params: new HttpParams().set('fileName', fileName),
reponseType: 'blob'
};
return this.http.get<Blob>(extractZip, httpOptions);
}
Angular service call :
this.myService.sendSql(this.sql, this.dataSource, this.fileGeneration).subscribe(data => {
if(this.fileGeneration) {
this.myService.getZip(data.zipName).subscribe(blob => {
console.log(blob);
console.log("Zip file download success.")
},
error => {
console.error(error);
console.log("Zip file download failed.")
});
}
},
err => {
console.log('An error occurred when contacting the application server.');
});
In summary, I use this.myService.sendSql() to retrieve the zip name which is then used with this.myService.getZip() for downloading the zip file.
The request URL looks like this:
http://localhost:8870/extracts_sql?fileName=name.zip
, and it works perfectly in the browser.
Here's the server-side code snippet:
@GetMapping("/extracts_sql")
public ResponseEntity<InputStreamResource> getFile(@RequestParam String fileName) throws FileNotFoundException {
Configuration configuration = ConfigurationHelper.readConfiguration(configurationFile);
MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
File file = new File(configuration.getProcessingFolder() + File.separatorChar + fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
log.i("Sending zip: " + fileName + " to user.");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(mediaType)
.contentLength(file.length())
.body(resource);
}
The problem arises when I receive a HttpErrorResponse on the Angular side, despite its status code being 200. The error message reads:
SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse Http failure during parsing for http://localhost:8870/extracts_sql?fileName=name.zip
. Any suggestions?