Attempting to retrieve a file from the database with the utilization of Angular 5 and ASP.NET Core

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.`);
        });
    }
}

Answer №1

Your C# code appears to be correct, however, your TypeScript/Angular code may not be triggering the GetDownloadFile action of your API.

When using the http.get(...) method, it returns an observable and the HTTP request will only be executed 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 the file data.
    });
}

If you need to save the file, consider using the file-saver package.

To install the package, run the following command in your project's root directory (where package.json is located).

npm install file-saver --save

Then, update your code to import and use the file-saver method to save the 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');
  });
}

I hope this information helps you resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

Record the stack trace and proceed with the operation

In a specific situation, I am required to log the stack trace instead of throwing an exception and continue with the execution. This is because the try and catch block is within a loop. Can anyone provide guidance on how to achieve this in C#? try {} Cat ...

Is there a way to retrieve the chosen value from an ion-alert radio alert?

async showAlertRadio(heading:string){ const alert = await this.alertCtrl.create({ header: heading, inputs :[ { name : 'Radio 1', type: 'radio', label: 'Radio 1', ...

The pre-installed ASP.NET Core + React template in Visual Studio 2019 is experiencing issues

After setting up a new project in Visual Studio 2019: choosing ASP.NET Core Web Application and using the React default template (The Weather Forecast one), I launched it without any modifications. The build process completed without errors, however, up ...

How to Publish an Angular 8 Application on Github Pages using ngh

Currently in my angular 8 project, I am encountering the following issue while running the command: ole@mkt:~/test$ ngh index.html could not be copied to 404.html. This does not look like an angular-cli project?! (Hint: are you sure that you h ...

Tips for addressing the ESLint issue stating that the package should be included in dependencies instead of devDependencies

Struggling to properly lint my React+Typescript project with ESLint. In one of my components, I'm utilizing the useParams hook from react-router. import { useParams } from 'react-router'; However, ESLint is throwing an error on that line: E ...

DevExpress - Choose multiple checkboxes within TreeList widget

Suppose I have a TreeList with 2 groups: teachers and students, each with a "Status" column. I am trying to create a button that selects all active teachers and students. https://i.sstatic.net/cIY2I.png This is my current implementation: public class Mat ...

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

Unable to retrieve a link from a textBox in C#, I am facing difficulty loading it

I have a question regarding pasting a link into a textbox and then loading it by clicking a button. I am unsure of the correct approach to take for achieving this functionality. public partial class Form1 : Form { public Form1() ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. https://i.sstatic.net/GaPW8.png https://i.sstatic.net/7d6Fm.png Here i ...

"Encountering issues while setting up membership with MySQL in a new ASP.NET Razor project

After creating a simple project with a fresh MVC4 razor web page and a new empty MySQL database, I encountered the following exception: System.Reflection.TargetInvocationException was unhandled by user code Message=Exception has been thrown by the target ...

Showcase the NLog trace information on a RichTextBox display

I am looking to show the NLog trace in a RichTextBox while the application is running. logger.Trace("This is a Trace message"); logger.Debug("This is a Debug message"); logger.Info("This is an Info message"); logger.Warn("This is a Warn message"); logger. ...

Disable JavaScript import optimization for a specific file in IntelliJIDEA

I recently came across a tutorial on Angular 2 Google maps that I was following: The tutorial included the following import statement: import { } from 'googlemaps'; However, I encountered a problem where IntelliJ recognized this as an empty im ...

Having difficulty adjusting the configuration settings for an embedded report within Angular 7

While attempting to integrate a Power BI report with Angular 7, I encountered an unexpected error when trying to configure the settings of the report. The error message stated: Type '{ filterPaneEnabled: boolean; navContentPaneEnabled: boolean; }&apos ...

I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs: component.ts ngOnInit(): void { this.getQueryCountriesList().subscribe(arg => { this.countryDatas = arg; }); this.getQueryNights().subscribe(obj => { this.nightDatas = obj; }); ...

The controller is executing the action method two times

My MVC controller's action is being triggered twice by my jQuery code. Upon investigation, I discovered that the link was being activated both by jQuery and the MVC view. $('.treeview-menu li a[name="environments"]').on("click", function () ...

Merging two promises into a single promise in Angular

In my application, I am facing a challenge with implementing a method named loadAll. What I need to accomplish is to make calls to 2 different HTTP methods in order to load the necessary data. Both of these methods return promises. However, when I attem ...