What is the best way to send parameters back to the backend in Spring Boot?

In the service below, I am passing 2 parameters from the front end:

uploadFile(fileName: string, fileAsBase64:string): Observable<any> {
    let params = new HttpParams();
    params = params.append('fileName', fileName);
    params=params.append('fileAsBase64 ',fileAsBase64 )

    return  this.http.post('/api/uploadFile', params, { responseType: 'text' });
  }

However, I am only receiving one parameter: fileName=test fileAsBase64=null

@PostMapping(value ="/api/uploadFile")
public String uploadFile(@RequestBody String name , String fileAsBase64) {
   
}

Answer №1

To improve your code structure, consider encapsulating your two parameters within a Data Transfer Object (DTO).

@PostMapping(value = "/api/v1/upload-file")
public String uploadFile(@RequestBody EncodedFile file)
{

}

record EncodedFile(String fileName, String fileAsBase64) {}

It is also recommended to version your API for better management.

Answer №2

To retrieve request parameter values in your Spring application, make sure to utilize the @RequestParam annotation.

For more information on how to properly use this annotation, check out this helpful resource:

Answer №3

Here is an example of how your function should be structured:

@PostMapping(value ="/api/uploadFile")
public String uploadFile(@RequestParam String fileName, @RequestParam String fileAsBase64) {   
}

Alternatively, you can use any name for the parameters, as long as it matches the names specified in the annotations:

@PostMapping(value ="/api/uploadFile")
public String uploadFile(@RequestParam(name = "fileName") String name, @RequestParam(name = "fileAsBase64") String file) {   
}

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

What is the method for obtaining or accessing the environment variable specified within the 'systemPropertyVariables' tag in the pom.xml file?

Is there a way to extract and access the environment variable set under the 'systemPropertyVariables' section in the pom.xml file? Take a peek at the snippet from the pom.xml. I am interested in retrieving the value of 'env' for use in ...

Triggering NGRX effects for all actions except a few

I have implemented a feature that manages session timeouts in my application. Once the timeout occurs, it triggers a logout action. However, there are certain pooling actions for counter updates that I want to exclude from this timeout mechanism. How can I ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

Techniques for sending an ID to retrieve data from an API endpoint in Angular

I am facing an issue where I need to pass an id property from one GET api to another GET api. Specifically, my code looks like this: https://jsonplaceholder.typicode.com/posts/${value} Here, '${value}' needs to be dynamically replaced by 1,2,.. ...

Tips for capturing the b-form-input event that triggers the deletion of the input value

I've been on a mission to uncover the secret behind detecting the event triggered by clicking the x icon in a b-form-input of the type 'search': https://i.sstatic.net/YSxjD.png template: <b-form-input id="filter-input" ...

Utilize Java Apache Mina FTP Server libraries for enhanced functionality

Seeking to develop an Android FTP Server App utilizing the Apache Mina FTP Server. The issue at hand is as follows: I am encountering difficulties with importing these libraries. I am faced with two potential errors: If the libs are not included in "Jav ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Utilizing TypeScript code to access updatedAt timestamps in Mongoose

When querying the database, I receive the document type as a return. const table: TableDocument = await this.tableSchema.create({ ...createTableDto }) console.log(table) The structure of the table object is as follows: { createdBy: '12', cap ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Using JAXB to marshal a primitive data type of considerable length

When trying to marshal a long primitive type using JAXB, I utilized the @XmlJavaTypeAdapter annotation to adapt non-String types to Strings. However, I encountered an error when attempting to do this for a long type. Why does this happen and how can I succ ...

Steps for utilizing a Get() method to view a response within Angular

I am having trouble with implementing an API call on a page and I'm unsure about what's wrong with the Subscribe/Observe method. Currently, this is the code that I have: import { Component, OnInit } from '@angular/core'; import { Ro ...

Comparing two arrays using the method arrayName.equals(arrayName2)

I came across the sentence "array1.equals(array2) compares whether array1 and array2 refer to the same array object" in my Java book, but I'm having trouble understanding it. Can someone explain when arrays refer to the same object? Thank you in advan ...

Displaying continuous hours on the X-Axis within a 24-hour time series using Recharts

I've been attempting to showcase server data on a scatter chart with multiple y axes, but I'm encountering issues with duplicate hours on the X axis: https://i.sstatic.net/Spd7u.png Here's the code snippet I have so far: <XAxis dataK ...

I have a question about an error message I received: The module 'DashboardModule' imported an unexpected directive 'BarChartComponent'. It is asking for a @NgModule annotation to be added

I'm encountering a compilation error with the code: 'BarChartComponent' imported by the module 'DashboardModule' is causing an unexpected directive error. Please make sure to include a @NgModule annotation. dashboard.modul ...

What is the reason behind requiring a variable declared within a method to be marked as final when being utilized in an inner class defined in the same method?

I hope you don't mind me bringing this up again, as I couldn't quite understand the reason behind it. Can someone please shed some light on this issue for me? For example: public class File { public static void main(String[] main) { ...

Checking for the presence of a pseudo element using selenium

Is it possible to detect the presence of a pseudo element like ::after or ::before? I am looking to simply determine if it exists, returning true or false. Unfortunately, traditional methods like: browser.driver.findElements(by.id('id')).size ...

React Router throwing an error about an Invalid Hook Call when attempting to use useState in index.tsx instead of App.js

I'm currently learning React Router by following a video tutorial, but I've run into an issue. In my Stackblitz project, there is no App.js file, so I've placed everything inside index.tsx. However, now I need to use the line ----> const ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

Interpolating linear transformations

How can I smoothly transition between two Java `AffineTransform` objects to make an image on the screen move from one position/rotation/scale to another with a matrix applied? I need this process to be efficient as it will occur every time a game is drawn ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...