What is the process for downloading a file in Angular from a response received from Java?

I am facing some troubles with downloading files in my Angular 7 app with Spring Boot at the back end. I save files in the resource folder and encounter issues while downloading them.

@RequestMapping(value = "/getfile", method = RequestMethod.POST)
    public void getFile(@RequestBody long id, HttpServletResponse response) {
        try {
            FileExpense fileExpense = fileExpenseRepo.findById(id).orElseThrow(() -> new CustomException(String.format("Договор (id:%s) не найден", id)));
                    if(fileExpense != null) {
                        File fileDownload = new File(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        response.setHeader("Content-Dispasition", "attachment; filename=" + fileExpense.getFileName());
                        response.setContentType("application/vnd.ms-excel");

                        OutputStream outputStream = response.getOutputStream();

                        Path path = Paths.get(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        byte[] data = Files.readAllBytes(path);
                        outputStream.write(data);
                        outputStream.flush();
                    }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }

and angular service:

public getFile(id: number): Observable<any> {
    return this.http.post('/expense/getfile', id);
  }

and download function in component:

downloadFile(fileJson: FileExpenseJson){
    this.expenseService.getFile(fileJson.id).subscribe(data => {
      let blob = new Blob([data.blob], {type: 'application/vnd.ms-excel'});
      let url = window.URL.createObjectURL(blob);
      let filename = fileJson.fileName;
      if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        let a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
      window.URL.revokeObjectURL(url);
    });
  }

this gives me error: message: "Unexpected token P in JSON at position 0" Please help . thanx anyway)

Answer №1

After much searching, I finally discovered a solution to my problem. The issue was that I forgot to include the options from the front-end with a response-type of 'blob'. Instead, it was sending the default JSON format instead of a blob.

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

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

What's the verdict on Ajax requests in Angular 4 - is $ajax superior to $http?

Instead of using $http to fetch data, I am utilizing $.ajax({}) in Angular 4. Is this a good approach for making AJAX calls? What is the recommended method for handling this task? Currently, I am employing this particular method for my AJAX requests. $. ...

iMask Angular plugin: the unmask feature prohibits typing

I've integrated the iMask plugin with Angular and encountered an issue when setting the value of the unmask attribute to 'typed'. This error only occurs with 'typed' as the value, not 'true' or 'false'. Here&ap ...

When uploading from Angular 2, PHP fails to populate the $_POST and $_FILES variables

I'm encountering difficulties when trying to upload files and data to my server using Angular 2 and PHP. After following the instructions in File Upload In Angular 2? to upload data and files from Angular 2, everything appears to be functioning corre ...

Traverse a nested array containing children elements to construct a pathway map

I am currently working with a multidimensional array that contains children (subcategories): As I am setting up Angular routing, I receive this data format from an API. const items = [{ displayName: 'News', urlName: 'news', subca ...

Revitalizing ngFor in Angular 9: Refreshing object properties for re-rendering

I am currently working with an array of objects named Guests: [ {id: 1, first_name: "Tom", last_name: "", logo: 2}, {id: 2, first_name: "John", last_name: "", logo: 3}, {id: 3, first_name: "Jim", l ...

MQTT: The method net.createConnection does not exist

Following the guide at https://www.npmjs.com/package/mqtt#install to establish an mqtt connection, I encountered a render error indicating _$$_REQUIRE_(dependencyMap[1], "net").createConnection(port, host)','_$$_REQUIRE(_dependencyMap[ ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Creating a dynamic button with routing capabilities

My current setup includes the Menu component. I want to ensure that when a link from the menu is active, the button should also show as active by changing its color. How can this be achieved? <button mat-button [matMenuTriggerFor]="menu" routerLi ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

What is the importance of having a generic Locals type Request in express?

As I was working on creating the properties of a Request object without using global declarations, I encountered a problem that threw me off course. I attempted to utilize the generic Locals for Request in order to set up the req.auth property, but unfort ...

Discovering the 3D coordinates of a point that is perpendicular to the midpoint of a line

(I am working with Javascript/Typescript and Three.js) Given two vectors, let's say {x:1, y:3, z:5} and {x:7, y:8, z:10}, I have a direct straight line connecting them. At the midpoint of this line, envision a disc with a radius of 1 that is perpend ...

Using Angular to send all form data to the API endpoint

Please bear with me as I am new and may ask small or incorrect questions. <form > <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:< ...

How to integrate a barcode reader into an Angular 4 application

I currently find myself in the process of integrating a barcode scanner into my Angular 4 project, with the assistance of this plugin - https://github.com/isonet/angular-barcode-scanner. Within my scanner.component.ts page, I have included: import { Comp ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Exploring RouteReuseStrategy in Angular 2

I followed the RouteReuseStrategy advice provided here, but had to make some adjustments. Specifically, I had to modify the handling of routeConfig.path in the shouldAttach method as it was empty and causing issues with caching. My Angular router version i ...

Understand and extract data from a JSON array using Typescript

Here is a JSON response I received from a remote server: { "string": [ { "id": 223, "name": "String", "sug": "string", "description": "string", "jId": 530, "pcs": [{ "id": 24723, "name": "String", ...

When setting up Angular material, be prepared for a thorough audit uncovering nearly 600 vulnerabilities

I want to utilize the drag and drop features provided by the @angular/material module, however, when I install it using angular cli, multiple vulnerabilities are flagged during the audit process. While the program functions as expected, attempting to run n ...

Incorporating a counter feature into an Angular HTML document

In this section, I am displaying the restaurants that are filtered based on their name and address. If no name or address is provided, all restaurants are shown. However, I am facing an issue as I need to incorporate a counter to keep track of the remainin ...

Discovering a div within an element using an Angular TypeScript directive

I've been working with TypeScript in an Angular project. Recently, I created a directive that consists of a div containing text and a close button with the class name 'block-close'. Now, my challenge is to implement a click function for th ...