How to fetch a file from a Spring Boot server using Angular 4

I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code:

Angular service:

getZip(fileName: string) : Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/zip',
        'Accept': 'application/zip'
      }),
      params: new HttpParams().set('fileName', fileName),
      reponseType: 'blob'
    };
    return this.http.get<Blob>(extractZip, httpOptions);
  }

Angular service call :

this.myService.sendSql(this.sql, this.dataSource, this.fileGeneration).subscribe(data => {
      if(this.fileGeneration) {
        this.myService.getZip(data.zipName).subscribe(blob => {
        console.log(blob);
        console.log("Zip file download success.")
        },
        error => {
        console.error(error);
        console.log("Zip file download failed.")
        });
      }
    },
    err => {
        console.log('An error occurred when contacting the application server.');
    });

In summary, I use this.myService.sendSql() to retrieve the zip name which is then used with this.myService.getZip() for downloading the zip file.

The request URL looks like this:

http://localhost:8870/extracts_sql?fileName=name.zip
, and it works perfectly in the browser.

Here's the server-side code snippet:

@GetMapping("/extracts_sql")
    public ResponseEntity<InputStreamResource> getFile(@RequestParam String fileName) throws FileNotFoundException {
        Configuration configuration = ConfigurationHelper.readConfiguration(configurationFile);
        MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
        File file = new File(configuration.getProcessingFolder() + File.separatorChar + fileName);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        
        log.i("Sending zip: " + fileName + " to user.");

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(mediaType)
                .contentLength(file.length())
                .body(resource);
    }

The problem arises when I receive a HttpErrorResponse on the Angular side, despite its status code being 200. The error message reads:

SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse Http failure during parsing for http://localhost:8870/extracts_sql?fileName=name.zip
. Any suggestions?

Answer №1

Here is the output:

return this.httpClient.get<Blob>(extractZip, httpOptions)

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

The function to increase the number of days on a date in Angular is experiencing technical issues

I'm facing an issue where I need to add 12 days to a specific date, but the new date is not coming out as expected. Below is the code snippet: addDays(days: number): any { let startDate = new Date(this.selectedDeliveryDate); let endDate = new ...

Problem with rendering React Router v4 ConnectedRouter on nested routes

The routes for the first level are correctly displayed from Layout.tsx, but when clicked on ResourcesUI.tsx, the content is not rendered as expected (see code below). The ResourceUI component consists of 2 sections. The left section contains links, and th ...

The compatibility issue between the text-mask library and the Angular material datepicker is causing functionality problems

I am currently utilizing the text-mask library (https://www.npmjs.com/package/angular2-text-mask) in an attempt to integrate it with two Angular datepicker components. The functionality works as expected when manually entering the date into the input field ...

Modifying the response header in a node.js middleware: A step-by-step guide

I've been researching this question extensively on Google, but unfortunately, none of the solutions seem to work for me. The issue I'm facing is related to adding a specific property to the response header called "isAuth," which needs to be set ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

Utilizing ES6 class methods as a parameter for Express routing

I'm having trouble passing a class method as an Express route parameter. I've attempted to bind the method and also tried using arrow functions, but neither approach has worked for me. My project involves TypeORM, and I keep encountering the err ...

"Comparing the use of single Angular libraries versus multiple libraries on npm

I am considering consolidating all my libraries (57 in total) into a single folder called @my-organisation/team. This is because each library has many dependencies on one another and managing versioning & dependencies separately would be difficult. After s ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...

I need my C# client application to handle the parsing of intricate JSON data being transmitted from a Java application

When deserializing complex JSON data from a Java server app to a C# client app, what is the most efficient option available? There are two key considerations: 1) Speed is of utmost importance. 2) The JSON format may contain information about Java data typ ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Jhipster entity authentication

For my latest project with JHipster, I decided to incorporate Angular 2 and MongoDB. One of the entities I created is a 'doctor' with attributes such as name (string), login (string), password (string), and specialty (string). Now I want to enabl ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Preventing duplicate requests when subscribing to an rxjs Observer multiple times

Currently, I am in the process of implementing a custom XHRBackend for my Angular 2 application. Here is the code snippet of the class: import {Request, XHRBackend, BrowserXhr, ResponseOptions, XSRFStrategy} from "@angular/http"; import "rxjs/add/operator ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...

Showing the contents of an array which contains arrays

Retrieves the elements stored in the history array. Each element of the history array is a separate array containing fields with names and values. The goal is to display this history table by iterating over each element of the array and displaying it in ...

Difficulty in HttpRequest handling between Angular and .Net

My http response seems to be causing some trouble, and I'm completely stumped on what the issue might be. Can someone provide assistance, please? import { Component, OnInit } from '@angular/core'; import {SharedService} from 'src/app/sh ...

Utilize ASP.NET Boilerplate Core and Angular on Microsoft Azure for seamless deployment

I am looking to deploy ASP.NET Boilerplate Core & Angular on Microsoft Azure. The current version of ASP.NET Boilerplate consists of two solutions (one for the backend and one for the frontend), so I need to deploy them on two separate AppServices along wi ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Ways to interpret and fix a conflict in npm dependency and understand the output

I'm encountering some issues while attempting to set up my project. The errors I'm running into during the installation process are: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/< ...

I am facing an issue with the asynchronous function as it is displaying an error message

**I am facing an issue with displaying categories. I have attempted to do this using async function, however the data is not showing up** <div class="form-group"> <label for="category">Category</label> <select id="categor ...