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

Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array. component.ts public checkDevi ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

Nuxt 3 turns a blind eye to TypeScript errors upon code saving

I am facing an issue. Even with a TypeScript error in the code, the IDE shows an error, but I am still able to save it and run it in the browser. Is this acceptable? Check out the code below: <script lang="ts" setup> const a = ref<strin ...

Uncovering a commitment to reveal the valuable information within

Whenever my Spring Boot back-end responds to front-end requests, it structures the data like this: { "timestamp":[2022,6,16], "status":"OK", "data": { "products": [{"product ...

Struggling with using Redux with tassign in Angular (typescript) to combine state.array and action.array. However, encountering an issue where state.array.join is not a function

Redux function to combine all videos: function combineAllVideos(state, action) { return tassign(state, { allVideos: state.allVideos.concat([action.data]) }); } Declaration + State for all videos array: allVideos: Array<Object>; OR allVid ...

When selecting a MenuItem, only a ReactOwner has the ability to add a ref using addComponentAsRefTo(...)

I'm currently working on a basic component that looks like this: class App extends React.Component<{}, {}> { constructor() { super(); } render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div> ...

Tips for updating form values with changing form control names

Here is an example of a form I created: public profileSettingsGroup = new FormGroup({ firstName: new FormControl('Jonathon', Validators.required) }) I also have a method that attempts to set control values in the form: setControlValue(contro ...

A guide to creating test cases for conditional statements in Angular using Jasmine

I am currently working on creating test cases for a custom directive in Angular. I have shared my code on StackBlitz. I would appreciate any guidance on how to address the highlighted if else statements below: if (trimmedValue.length > 14) { // Loo ...

What methods are called in an interface during Runtime?

Exploring the documentation for the OnTouchListener reveals a clear explanation: The OnTouchListener is triggered when a touch event is sent to a view. Understanding this concept makes perfect sense. I wish all interface methods had such straightforwa ...

The PrimeNG Tree component offers a range of unique features

Encountering an issue with the PrimeNG tree in angular2 Let's take a look at the code snippet from product_tree.component.ts : constructor(private http: HttpClient, private productsService: ProductsService) { this.productsService.getProductsClasse ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Difficulty with setting up Typescript in Visual Studio Code on MacOS Catalina

I'm currently facing an issue that appears to be related to the environment. How can I resolve it? And how do I link the installed TSC to my console? Steps to Recreate: npm install -g typescript was able to successfully install or update [email ...

Is there a way to merge TypeScript code with C++ during compilation?

Currently, I have a project written entirely in C++. However, there is an additional file written in typescript because I couldn't find equivalent libraries in C++. This typescript file performs the following actions: It contains a typescript CLI cod ...

Angular's array filter functionality allows you to narrow down an

I am working with an Array and aiming to filter it based on multiple criteria: primasSalud = [ { nombre: 'one', internacional: true, nacional: false, nacionalSinReembolso: false, nacionalClinicasAcotadas: false ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Is it possible to extract a single element from an array that is stored as a standard Observable?

Currently, I am using a regular observable instead of an observableArray. This observable keeps an array of elements which is defined as follows: public arrayOfItems: IArrayItem[]; public arrayOfItems$: BehaviorSubject<IArrayItem[]> = new BehaviorSu ...