Is it possible to upload a file using @PathVariable in Spring?

My dilemma involves an ajax post that sends certain values from a URL:

var sendUrl = url + ',' + testId + ',' + questionId + ',' + questionRevision + ',' + result;   
 var ajaxData = {
                type: "POST",
                contentType : 'application/json; charset=utf-8',
                dataType : 'json',
                data: requestData,
                url: sendUrl,
                headers: headersData,
        };

and links them with @PathVariable in the following manner:

@RequestMapping(value="/answer,{testId},{qid},{qrev},{qres}", method = RequestMethod.POST)
    public @ResponseBody String answer(HttpServletRequest request, 
                            @RequestBody List<NokDataDTO> nokInfoDtos ,
                            @PathVariable("testId") Long testId,
                            @PathVariable("qid") Long qid,
                            @PathVariable("qrev") Integer qrev,
                            @PathVariable("qres") Integer qres) 

In this scenario, I am wondering if there is a way to pass an image file using @PathVariable. Although I can fetch the uploaded file from JavaScript like this:

var fileVal=document.getElementById("fileLoader").files[0];

I am unable to figure out how to bind it through RequestMapping.

Answer №1

When it's time to transfer the data to the server, you can retrieve the file from the element by accessing the element.files[0] property and then converting it into a base64 string. This encoded string can then be sent to the server along with your other values.

const chosenFile = document.getElementById("fileLoader").files[0];

const reader = new FileReader();
reader.readAsDataURL(chosenFile);
reader.onload = function() {
  // Send to server
  const convertedImg = reader.result;
};
reader.onerror = function(error) {
  console.log('Error: ', error);
};

Answer №2

After some research, I managed to find a solution utilizing the power of javascript FormData(). By fetching the file and adding all necessary values to the FormData object, you can then submit it like so:

   const file=document.getElementById("fileLoader").files[0];
        var fd = new FormData();
        fd.append('photo', file);
        fd.append('testId', testId);
         var ajaxData = {
            type: "POST",
            data: fd,
            processData : false,
            contentType : false,
            url: sendUrl,
            headers: headersData,
    };

On the server-side, make sure to map them correctly with param names:

@RequestMapping(value="/response", method = RequestMethod.POST)
    public @ResponseBody String response(HttpServletRequest request, 
            @RequestParam(value = "photo") MultipartFile photo,
            @RequestParam(value = "testId") String testId

This approach proved successful for me.

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

Use JavaScript to retrieve a value and display it on a PHP page

I am trying to create a system that can generate and deliver JSON data. Here is the PHP code I have so far: <?php header("Content-Type:application/json"); require "data.php"; if(!empty($_GET['name'])) { $name=$_GET['name']; ...

How to Access Data Attribute in React TypeScript on Click Event

Recently, I encountered a situation with my React component where I have a button with a click handler that utilizes the data-* attribute. In the past, with regular React, extracting the value from the data-* attribute was straightforward. However, as I am ...

Variables with a global scope within a module

Is there a way to declare a global variable that can be accessed inside a specific module? For example, if we have a module called "test" with files index.js, test1.js, and test2.js, can we define a variable inside index.js that is accessible in test1.js a ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

Transforming JSON data into HTML code

I am looking to transfer a list of songs from a JSON file to specific HTML ids using a jQuery function. In the JSON file, there are five songs, and here are two of them in the same format: { "songs": [ { "title": "Bohemian Rhapsody ...

How can JSON objects be structured to reflect the Map collection type for the specified pattern?

Creating nested HashMaps in Java can be a complex task but doesn't have to be. In this example, we have multiple levels of nested HashMaps with key-value pairs. Now the question arises - how do we serialize this data into a JSON object? If you have a ...

What is the proper way to utilize the value of a Node.js promise in a different function?

In my Node.js application, I have two functions defined. The first function is structured like this: function checkAdd ( address /* : string | void */ ) /* :Promise<Object[]> */ { var convertToLowerCase = address.toLowerCase() return Promi ...

What is the best way to retrieve accurate boolean field values using an ORMLite raw query?

Using ORMLite with an H2 database in Java poses a challenge for me. Specifically, I have a class featuring a boolean field. The issue arises when utilizing a raw query and the DAO's default raw row mapper to retrieve an object of this class from the d ...

Enhance your Magento store with Ajax-based attribute filters

I am in need of setting up a series of dropdown menus that are interlinked, such as Truck Brand, Truck Model, and Model Years. There will be a dropdown menu for Brand initially, containing all the available options for Truck Brands. Once a Brand is select ...

Successive jquery functions are executed independently upon being called

I've encountered a simple problem that has stumped me despite trying various approaches to consolidate these functions in one HTML file. The issue arises when the first function is invoked, causing the second function to execute simultaneously and lea ...

I am looking to implement a permanent change using PHP Ajax

I am facing an issue with the "Add as Buddy" button on my webpage. I want it to change permanently to "Pending Request" once clicked, but it keeps reverting back to "Add as Buddy" whenever I refresh the page. Can anyone suggest a solution for this problem? ...

Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node. From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Altering the JavaScript variable by selecting an option from a dropdown list

After downloading a choropleth map from leafletjs.com, I encountered an issue with multiple JS files labeled by year (e.g. us-states2012.js, us-states2013.js). The challenge now is to implement a drop down menu in such a way that selecting a specific year ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

running a function during the import process in ecmascript

When it comes to importing modules the traditional way, we usually do it like this: var a = require('a') If we want to export a function from the 'a' module, we do it like: var a = require('a')(); But how can we achieve ...

Exploring Vaadin 14 Slider Components

I'm looking for help on how to incorporate a slider into my Vaadin 14 project. I discovered that the slider component was removed in Vaadin 10, so I turned to this alternative: Once I added the Maven dependency and repository to my pom.xml, I success ...

Exploring options for adopting a distributed MVC pattern with the use of distributed caching systems

Currently, I am in the process of developing a client/server application that will feature a relatively intricate (though not massive - around 10,000 objects) object model at its core. The model will be accessed by multiple clients through an Eclipse RCP G ...

Switch between two functions by clicking a button

Presented here is a button that serves as a toggle switch: <button ng-click="togglefunction()">Toggle Data</button> Below is the toggle functionality: $scope.toggleToolPanel = function () { // The goal is to include the following 2 ...

Can CSS be altered dynamically in Laravel blade?

Is there a way to dynamically change CSS? I am trying to set the class=sheet padding-top: 28mm; when the size of $anArray is less than 30. If the array has more than 30 elements then apply padding-top: 28 * 2 mm;. Finally, if the array exceeds 60, use pad ...