Blob is unable to open the PDF file as it is not

Currently, I am utilizing ASP.NET Core and Angular to create a web application. In one of the controller actions, I am returning a File like this:

return Ok(Microsoft.AspNetCore.Mvc.File(await GetFileContents(args), "application/pdf"));

Then in TypeScript, I am reading the contents as shown below:

this.myService.getPDFFile(requestData)
    .subscribe(data => this.downloadFile(data))

private downloadFile(data: any) {
       const blob = new Blob([data], { type: 'application/pdf' });
        saveAs(blob, 'result.pdf');
}

Upon inspecting the data contents, I can see the bytes displayed as follows:

{
  "fileContents": "JVBERi0xLjQNCiWio4+TDQo0IDAgb2JqDQo8PC9UaXRsZSA8RkVGRj4gL0F1dGhvciA8RkVGRj4gL1N1YmplY3QgPEZFRkY+IC9LZXl3b3JkcyA8RkVGRj4gL0NyZWF0b3IgPEZFRkY+IC9Qcm9kdWNlciA8RkVGRjAwNDQwMDY1MDA3NjAwNjUwMDZDMDA2RjAwNzAwMDY1MDA3MjAwMjAwMDQ1MDA3ODAwNzAwMDcyMDA2NTAwNzMwMDczMDAyMDAwNDkwMDZFMDA2MzA..",
  "contentType": "application/pdf",
  "fileDownloadName": "",
  "lastModified": null,
  "entityTag": null,
  "enableRangeProcessing": false
}

However, when attempting to open the saved PDF file, it shows as invalid. What could be the issue here?

Answer №1

To retrieve the desired output, your controller must return:

   return File(fileResult.File, fileResult.FileMime, fileResult.FileName);

This code snippet is from one of my previous projects. It fetches a file, generates a hidden <a></a> element with target attribute set to _blank, and programmatically triggers a click event on the anchor to open the document in a new tab.

  private downloadFile(request: ContractDocument): void {
    this.documentService.download(request.id).subscribe({
      next: (data) => {
        if (!data) {
          return;
        }
        let downloadedFile: Blob;
        let a: HTMLAnchorElement;
        switch (data.type) {
          default:
            break;
          case HttpEventType.Response:
            this.isDownloading = false;
            downloadedFile = new Blob([data.body!], {
              type: data.body!.type,
            });
            a = document.createElement('a');
            a.setAttribute('style', 'display:none;');
            document.body.appendChild(a);
            a.download = request!.fileName!;
            a.href = URL.createObjectURL(downloadedFile);
            a.target = '_blank';
            a.click();
            document.body.removeChild(a);
            break;
        }
      },
      error: (error) => {
        this.showError(error);
        this.isDownloading = false;
      },
    });

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

Detection of compile-time errors in ASP.Net MVC due to incorrect model usage

Is there a method to receive compile time errors for strongly typed views? Suppose there is a view stored in the directory /Views/Home/Index.cshtml with the following code & a strongly typed Model: @model CSTemplate.Models.Home.HomeIndexModel @{ ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Customizable mongoDB database collection

Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case. Currently, I have this code and the goal is to have a u ...

How can you effectively structure SQL queries for maximum efficiency?

There are multiple SQL queries stored as strings in our code: public class Query { public static string CreditTransferId(string expectedValue, string table, int statusId, int messageTypeId, int destination103, int destination202, string StoreStatu ...

Tips for effectively handling projects that call for varying versions of TypeScript within Visual Studio

In some cases, developers have had to downgrade their TypeScript version in order for it to work with a specific npm package version. Is it possible to do this with Visual Studio? I recently obtained a sample solution that utilized the angular2 npm packag ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component. The login component is located in the directory app/main/login. I am trying to navigate to the login component from app.component.html using a button. Below is the code snippet from my app-routi ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...

Prioritize the timepicker over the use of a modal window

Having an issue with my time picker in Angular being blocked by a modal window. Component.ts open() { const amazingTimePicker = this.atp.open(); amazingTimePicker.afterClose().subscribe(time => { console.log(time); }); } // T ...

Discover the steps to initiate Firefox in Incognito Mode using NodeJS and Selenium!

Can anyone help me figure out how to launch Firefox in private mode using TypeScript? I have attempted the following code but it doesn't seem to work: static async LaunchFirefoxInPrivateMode():Promise<WebDriver> { //Setting up firefox capab ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Learn how to implement React Redux using React Hooks and correctly use the useDispatch function while ensuring type-checking

I'm curious about the implementation of Redux with Typescript in a React App. I have set up type-checking on Reducer and I'm using useTypedSelector from react-redux. The only issue I have is with loose type-checking inside the case statements of ...

The attribute 'map' is not found in the object 'MapPage'

I'm currently facing a challenge with integrating Google Maps into my Ionic 2 application that is based on the Tabs template. Everything was functioning properly until I attempted to initialize the this.map method within the constructor function. im ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...

The cookie value is blank once after moving to the second page

I'm facing an issue with 2 domains where performing an action on the first domain results in setting a cookie that should be accessible on both domains. However, when trying to read the value of this cookie on the second domain, it appears empty. Can ...