Extracting and passing a JSON object to a Spring controller

I have a file upload feature on my jsp page that specifically accepts json format files. I want to retrieve the uploaded json file and pass it to a Spring controller for further processing.

This is how my javascript code appears:

var file = this.files[0];
 var reader = new FileReader();

  var oMyForm = new FormData();
  oMyForm.append("file", this.files[0]);

 console.log('reader='+JSON.stringify(reader)) // The output is empty - "reader={}"
console.log('oMyForm ='+JSON.stringify(oMyForm )) // The output is empty - "oMyForm={}"
var urlpath =  "<%=request.getContextPath()%>/fileUpload";
  $.ajax({
                    data : JSON.stringify(reader),
                    type : 'POST',
                    dataType: 'json',
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    url : urlpath,
                    success : function(data){
                    }
               });

This is my Java class:

@RequestMapping(value= "/fileUpload", method=RequestMethod.POST,consumes="application/json")
    public void fileUpload(){
         //I need to retrieve the json object here and perform parsing and manipulations on it
         System.out.println("File uploaded!");
    }

Despite the file successfully reaching the controller, the browser console displays the error:

"NetworkError: 404 Not Found - http://localhost:8080/proj/fileUpload"

Interestingly, hardcoding a value for JSON.stringify(hardcoded) works fine.

Json file content:

{'Gyr-x':10.11,'Gyr-y':9.66,'Gyr-z':10.93,'Temparature':30,'Pressure':101,'Humidity':15,'deviceId':1}

Answer №1

@RequestMapping(value= "/fileUpload", method=RequestMethod.POST,consumes="application/json")
public void fileUpload(@requestBody String json){
     //Perform JSON object parsing and manipulations here
     System.out.println("File uploaded successfully!");
}

For the JavaScript part, make sure to use url:fileUpload

If your page is giving a 404 error, it might be because the controller is not being accessed properly

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

How can I transfer the total and counter values to a different PHP page and store them in a text box before saving them to the database?

I need to transfer the total and counter values to another PHP page using a text box and then save them to a database. { var price =10; //price $(document).ready(function() { var $cart = $('#selected-seats'), //Sitting Are ...

I am facing an issue where my Popover functions correctly when elements are added using HTML, but not when they are dynamically created

I'm currently working on a method to incorporate multiple popovers that have a similar appearance to the following: The screenshot of my first JsFiddle project (click to view) The initial progress I've made can be seen in my first JsFiddle, acc ...

What is the best way to extract the value associated with the "first_name" key in the given object?

What is the best way to extract the value associated with the first_name key from the object below? { "first_name": "D", "last_name": "N", "phone_number": 1233414234 } ...

A many-to-many relationship does not introduce additional entities into the database table

I am dealing with two entities, Book and BookTag, that are connected through a many-to-many relationship. @Getter @Setter @Entity @NoArgsConstructor @AllArgsConstructor @Builder(toBuilder = true) @Table(name = "books") public class Book { @Id ...

How to use node.js to add JSON data to a JSON file without using an array?

I'm trying to update a JSON file without using an array with FS. The desired format of the file should be: { "roll.705479898579337276.welcomemessage": "There is a welcome message here", "roll.726740361279438902.welcome ...

Tips for sending arguments to an async function

I am currently facing an issue in my vue.js application where I am struggling to access the value of name that is being passed to my function. My hunch is that this issue is related to scope. After some research, it seems like using a fat arrow function mi ...

Turn off Satellizer Popup Window Title Bar

Currently, I am implementing the satellizer plugin for Facebook authentication. However, I have encountered an issue with the default popup login window of Facebook, which includes a title bar and menu options. I would like to transform this popup into a m ...

now.js - There is no method in Object, however the click event works in jQuery

Here is a simple NowJS code snippet for the client side: $j(document).ready(function() { window.now = nowInitialize('http://xxx.yyy:6564'); now.recvMsg = function(message){ $j("body").append("<br>" + message); } $ ...

An AJAX request was dispatched to the identical PHP script

At the moment, I am working with a single PHP file named createNewForm.php. Within this file, there is a series of checkboxes that, when checked, should trigger an SQL query to repopulate a list within the same PHP file. For instance, if I check 'Ani ...

Switching the background color of a <td> based on an array provided in the AJAX response

My goal is to dynamically change the background-color of elements based on values in an array. However, I am facing a problem where all elements are displaying with the same color instead of changing according to the value. I have attempted using jQuery w ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Unit testing component in Ionic 2 with Ionic's specific markup and elements

Within my Angular 2 component for an Ionic 2 app, I utilize Ionic's markup as shown below: <ion-card> <h3>{{ rawcontent.name }}</h3> <p *ngIf="rawcontent.description">{{ rawcontent.description }}</p> </ion-car ...

In search of a way to verify if a string contains a specific word

I'm currently working on a dynamic tooltip feature. My goal is to detect multiline tooltips by checking if my data includes \r. The code snippet below is an example of how I am trying to analyze my description, but so far, I have been unsuccessfu ...

If a dynamic route does not exist in NextJS, display a 404 error. Otherwise, show a loading spinner

I am facing an issue with the dynamic routes in my NextJS app, specifically /team/[id]. When the page loads, it queries the API to retrieve information based on the team ID. If the ID does not exist in the API, a 404 error is returned. However, I am strugg ...

The art of concealing and compressing JavaScript code

Can modern JavaScript obfuscation and minification tools effectively protect my code from reverse engineering? Which obfuscation platforms are the most reliable in thwarting these attempts? Is it possible that a program could easily deobfuscate the code, ...

Automated pagination in Jquery running seamlessly

I have successfully created pagination using jQuery. Although the script is functioning properly, I now want it to automatically switch between different pages: <script> $(document).ready(function(){ $("#article_load_favourites").load("indexer_favo ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

How can components be utilized with v-edit-dialog?

Hey there, I've been exploring the v-edit-dialog component offered by Vuetify and had a query about its implementation. Currently, I'm structuring my v-data-table in a way where I'm importing a component with props into a template slot. The ...

Enclose an image with a <div> element while maintaining the <div> height at

Encountering a challenge where positioning an element on top of an image at specific coordinates (20% from the top and 30% from the left) is required. Initially, the solution involved wrapping the image in a div with a relative position and using absolute ...

Implementing OPTIONS request header support in an aspx page

Currently, I am working on a service that can handle form posts. While adding support for CORS requests, I encountered an issue in Firefox 3.6 where it sends a preflight request with an OPTIONS request header. Though I managed to add the necessary Access- ...