How can I send a file and a string request using the POST method to a Spring REST controller that accepts byte[] and Strings with Angular

Need help with sending a post method that includes a file and another string request parameter to a spring rest controller using angular.

The server controller parameter is set up to receive an array of bytes for the file and another string request wrapped in one entity. I've been struggling with this problem for 2 days now and haven't found a solution yet.

Attached below are images of the controller, encapsulated request entity, the post method implemented using Angular resources, and the error from the server:

https://i.stack.imgur.com/jnnb6.png

Answer №1

To accomplish this task, I personally handled the conversion process myself. In JavaScript, I first convert my file into base64 and then further convert it into a byte array in the Spring controller using javax.xml.bind.DatatypeConverter.parseBase64Binary().

Here is the custom JavaScript code for manually converting your file into base64:

$scope.onFileSelect = function(ele){
    $scope.files = ele.files;
    var reader = new FileReader();
    reader.onload = function(e){
        console.log("about to encode");
        $scope.encoded_file = btoa(e.target.result.toString());
    };
    reader.readAsBinaryString($scope.files[0]);
    $scope.fileBase64 = new FileReader();
    $scope.fileBase64.readAsDataURL($scope.files[0]);
    console.log("$scope.fileBase64: ",$scope.fileBase64);
};

You should also include the on-change attribute in your file input HTML like so:

<input id="Data" type="file" multiple onchange="angular.element(this).scope().onFileSelect(this)">

In the Spring controller itself, simply change the request file to String that is encapsulated within one entity:

@RequestBody PositionNew positionNew

The PositionNew entity contains attributes:

private String base64File;
  private String attr1;
  private String attr2;

That's all.

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 passport.use method is failing to invoke in Node.js when utilizing the passport-local strategy

Upon calling the login and submitting the form, it seems that the use.authenticate() method is not being executed and no error messages are displayed. Server.js code snippet: const passport=require('passport'); const Strategy=require('pass ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Encountering an issue with the history module when utilizing the webpack dev server

I am encountering an issue while trying to run webpack dev server. The history functionality was working fine until I started using the webpack module. A warning message appeared in my console: WARNING in ./src/history.js 2:15-35 export 'createBrows ...

Sending Three.js meshes to a web worker through JavaScript

I have a collection of objects, which are meshes generated using Three.js, that I need to perform operations on within a web worker. My question is, how can I send these objects to the worker? My understanding is that there's a concept called transfe ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

Utilizing ng-switch for handling null values or empty strings

Can anyone assist me with this issue? I have a variable called $rootScope.user = {name:"abc",password:"asd"}. When a service response occurs, I am dynamically creating a rootscope variable by assigning it. How can I use ng-switch to check if the variable h ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Tampermonkey only allows jQuery Click to execute once within a for loop

Attempting to switch the content of a text area to different cars and then trigger a button click to perform an action, repeating this process for each car until all cars have been processed. var index; var cars = ["car1", "car2", "car3"]; var x = documen ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

Loading a .css file in advance using NextJS

We have integrated NextJS and Material-UI into our website, but we are facing an issue with FOUC (Flash of Unstyled Content) upon page loading. After some investigation, I discovered that the JS files are loading faster than the CSS file, causing the probl ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

Incorporating filters within ui-sref for enhanced functionality

After coming across this answer, I realized it doesn't address my specific issue. My goal is to have the complete state name generated by my filter, rather than just using the filter for state parameters. Is there a way to use a filter to generate th ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

JavaScript function returning code

I am trying to create a JavaScript object with multiple functions, but I keep encountering an exception undefined is not a function Here is my JS code: var Cars = null; $(function () { Cars = function() { return { ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...