Hello everyone I'm trying to download a file using this method in my controller :
[HttpGet]
[Route("download/{id}&{bid}")]
public async Task<IActionResult> Download(int id,int bid)
{
string filePath = _context.ConnectionDB.FirstOrDefault(r => r.Id == id).FolderName;
string fileName = _context.SavedBackups.FirstOrDefault(r => r.Id == bid).PathOfSave;
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath+fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
When debugging I get the Path of the combination: filePath+fileName
, and my fileBytes contain values.
Anyway when I try using this on my FrontEnd client:
I'm using this function in my service to get the info from my backend:
downloadBackupDB(dbConn: DBconnection, idSave: number): Observable<any> {
const url =
`${this.backupRestoreUrl}/` + `download/` + `${dbConn.id}&${idSave}`;
return this.http.get(url);
}
And in my component I have tried to view the response value with this function:
onDownload(idOfDownload) {
console.log('Download file id:', idOfDownload);
console.log('Conn id:', this.dbConn.id);
this.dbConnService
.downloadBackupDB(this.dbConn, idOfDownload)
.subscribe((res) => {
console.log('resultat:', res);
const blob = new Blob([res], { type: 'application/octet-stream' });
this.sanitizer.bypassSecurityTrustResourceUrl(
window.URL.createObjectURL(blob)
);
});
}
But it's giving me the following error:
If there is a better solution or any ideas don't hesitate to share with me and the community, thanks everyone ! :)
I have tried using this example which apprentelly does work: example
EDIT: (this worked for me)
I have changed my function in the service into:
downloadBackupDB(dbConn: DBconnection, idSave: number): Observable<any> {
const url =
`${this.backupRestoreUrl}/` + `download/` + `${dbConn.id}&${idSave}`;
return this.http.get(url, { responseType: 'blob' });
}
And my function in the component to:
onDownload(idOfDownload) {
console.log('Download file id:', idOfDownload);
console.log('Conn id:', this.dbConn.id);
this.dbConnService
.downloadBackupDB(this.dbConn, idOfDownload)
.subscribe((res) => {
console.log('res:', res);
window.open(window.URL.createObjectURL(res));
});
}
Now it gives me the file to download but in a different name:
But in the function on the Backend I'm returning my file name, how do I get it now?