I've been struggling with downloading a file from the database using its unique identifier. Can anyone provide guidance on what steps are necessary to achieve this successfully?
The FileUpload table contains the following columns pertaining to the file:
Id = uniqueidentifier,
Content = varbinary,
ContentType = nvarchar (e.g. application/pdf),
FileName = nvarchar (e.g. filename.pdf),
FileType = tinyint
Below is the method specified in the Controller.
/// <summary>
/// Download the file from the database based on id.
/// </summary>
/// <param name="id">The unique identifier.</param>
/// <returns>The downloaded file.</returns>
[HttpGet]
public async Task<ActionResult> GetDownloadFile(Guid id)
{
if (id == null)
{
throw new UserFriendlyException("File not found.");
}
var file = await _fileUploadRepository.FirstOrDefaultAsync(id);
var filename = file.FileName.ToString();
var fileBytes = file.Content;
return File(fileBytes, file.ContentType,file.FileName);
}
Here is the TypeScript code attempting to invoke the controller function, although encountering issues (relevant excerpts included):
constructor(
injector: Injector,
private _fileUploadsServiceProxy: FileUploadsServiceProxy,
private _notifyService: NotifyService,
private _tokenAuth: TokenAuthServiceProxy,
private _activatedRoute: ActivatedRoute,
private _fileDownloadService: FileDownloadService,
private _searchService: SearchService,
private http: Http
) {
super(injector);
}
/// <summary>
/// Method for downloading a file from the database.
///</summary>
///<param name="file">The file object to be downloaded.</param>
downloadFile(file: any): void {
if (file.fileUpload.id) {
var headers = new Headers();
headers.append('Content-Type', file.fileUpload.contentType);
headers.append('Authorization', 'Bearer ' + abp.auth.getToken());
this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${file.fileUpload.id}`, {
headers: headers,
responseType: ResponseContentType.Blob
})
.subscribe(result => {
saveAs(result.blob(), file.fileUpload.fileName);
this.notify.success(`Downloaded ${file.fileUpload.fileName} successfully.`);
});
}
}