nless
nless

Reputation: 166

Trying to download file from database using angular 5 and asp.net core

I am trying to download a file that has been uploaded successfully to a database by id. Does anyone know what is needed to be done to get the correct outcome?

I have a FileUpload table that has the following columns (related to the file):

Id = uniqueidentifier,
Content = varbinary,
ContentType = nvarchar, e.g. application/pdf
FileName = nvarchar, e.g. filename.pdf
FileType = tinyint 

Here is the method in the Controller.

/// <summary>
/// Download the file from the database by id.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>The 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 trying to call the controller but it doesn't work (I've only included relevant code):

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> 
/// Download the file from the database.
/// </summary>
///<param name="file">The file.</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.`);
        });
    }
}

Upvotes: -1

Views: 738

Answers (1)

user4717662
user4717662

Reputation:

You C# code seems correct, but you TypeScript/Angular code will not call the GetDownloadFile action of you API.

The http.get(...) method returns an observable and the HTTP request will only be fired when you subscribe to it.

public downloadFile(id: number): void {
  var headers = new Headers();
  headers.append('Content-Type', 'application/octetstream');
  headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

  this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`)
    .subscribe(result => {
      // result contains your file data.
    });
}

Now, you will need to save your file, you can use the file-saver package.

Install the package using the following command in your project root directory (where package.json is located)

npm install file-saver --save

And then update your code to import and call the file-saver method to save your file.

import { saveAs } from 'file-saver';

public downloadFile(id: number): void {
  var headers = new Headers();
  headers.append('Content-Type', 'application/octetstream');
  headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

  this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`).subscribe(result => {
    saveAs(result, 'fileName');
  });
}

Hope it helps.

Upvotes: 2

Related Questions