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

Middleware in Expressjs ensures that variables are constantly updated

I'm attempting to accomplish a straightforward task that should be clear in the code below: module.exports = function(req, res, next) { var dop = require('../../config/config').DefaultOptions; console.log(require('../../config/ ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Discover the method to adjust the position of elements, such as images, using radio buttons

I have an image positioned in a container along with 3 radio buttons. I want to make additional images appear over the main image when specific radio buttons are selected. Each button will trigger different positions for the additional images. So far, thi ...

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

What is the best way to transform an array of arrays into an array of objects using AngularJS?

Here is some code I am working on: $scope.students=[]; $scope.students[[object Object][object Object]] [0]{"id":"101","name":"one","marks":"67"} [1]{"id":"102","name":"two","marks":"89"} I would like to reformat it into the ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

Error occurred while trying to fetch the Backbone.js collection due to undefined value of 'this._byId'

I am currently working with coffeescript and my code is quite straightforward: class SomeCollection extends Backbone.Collection constructor: (@options) -> url: -> "#{$SCRIPT_ROOT}/some/data/#{@options.someId}" model: SomeModel class SomeV ...

Retrieving the date input from a React form powered by Bootstrap

Is there a way to extract a specific timestamp in the format yyyy-mm-dd from the code snippet below? handleDateChange = e => {} <Form.Group as = {Col}> <Form.Control type = "date" value = { this.state.closingDate } onChange = { ...

Having difficulty creating a shadow beneath a canvas displaying Vega charts

I'm looking to create a floating effect for my chart by adding shadows to the canvas element that holds it. Despite trying various methods, I can't seem to get the shadow effect to work. Here is the code snippet I have for adding shadows: <sc ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Is there a method to refresh the entire DOM-based location without having to reload the browser window?

Is it possible to achieve smooth asynchronous page transitions without breaking existing JavaScript animations in a system like Webflow? I'm struggling to find a way to present new elements to the DOM without disrupting the animations that are already ...

Submitting data twice through AJAX POST requests

Using a PHP file called via AJAX to insert data into MySQL. Prior to the insert statement, the PHP code runs a select query to check for duplicate records and then proceeds with the insert statement. Problem: When calling the PHP file from AJAX, it gets ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly This is my implementation of the Config factory (function() { 'use strict'; angular.module('commercial.factories').factory(&apos ...

Using jQuery to retrieve the HTML code for links

I am looking for a way to extract HTML links from a specific div without relying on regular expressions. Here is an example scenario: <div>Please review the links provided in the content. For instance, <a href="http://en.wikipedia.org/wiki/Apple ...

What could be causing the issue of angular data-binding not functioning properly in conjunction with jquery

Currently, I am working on the angular tutorial project known as angular-phonecat, and I have reached step 5. Out of sheer curiosity, I decided to replace the original angular ajax method with a jquery ajax method while keeping everything else unchanged. ...

How to effectively refine a group query in Firestore to obtain specific results

My database structure is set up like this (simplified version): Collection: item_A -> Document: params = {someParameter: "value"} -> Document: user_01 -> Sub-collection: orders_item_A -> Document: order_AA ...

Bidirectional Data Binding in Angular-Kendoui for the Treeview Data Source

Check out this example I created: It's built on kendo's TreeView angular example. The issue here is that the model doesn't update when the checkboxes are checked or unchecked. Do you have any suggestions on how to make the two-way bin ...