Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API.

During debugging, I noticed that the control is not reaching the Java file. Can someone please assist me in figuring out what might be wrong in my code?

myfile.html

Label of File: <input type="text" name="iconlabel" data-ng-model="imporLabelName"><br>
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>
<button type="button" class="btn btn-primary pull-right" data-ng-click="uploadfile();">Submit
                </button>

myFileController

define([ '{angular}/angular' ], function(angular) {
var module = angular.module('myFile', [ 'ngResource', 'colorpicker-dr' ]);

module.controller('myFileController', [ '$scope', '$sce', '$http', '$location', '$window', 'w20MessageService'
,function($scope, $sce, $http, $location, $window, w20MessageService) {
    
            var config = { 
                    headers: {
                        "Content-Type": undefined,
                    }
                };
       
            /*** Modale for MyFile **/
            $scope.openMyFile = function() {
                $("#myfile").modal("show");
            };
            
            $scope.uploadfile = function() {
                $scope.file = document.getElementById('myFile').files[0];
                alert('LabelName = '+$scope.imporLabelName);
                
                var formData = new $window.FormData();
                formData.append("label", $scope.imporLabelName);
                formData.append("file", $scope.file);
                alert('File = '+$scope.file);
                var url = "uploadfile/label="+$scope.imporLabelName;
                alert("URL = "+url);
                $http.post(url,$scope.formData,config).success(function(response) {
                    $scope.result = "SUCCESS";
                }).error(function(response, status) {
                    if (status === 400) {
                        w20MessageService.addMessageErreur(data.message, "msgGererParam");
                    } else {
                        w20MessageService.addMessageErreur("eox.message.error.load.traitement", "msgGererParam");
                    }
                });
              $("#myfile").modal("hide");
            };
        } ]);
return {
    angularModules : [ 'digitalJes' ]
};
});

java api code

@POST
@Path("/uploadfile/{label}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(@PathParam("label") String label, @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition fileInputDetails) {

    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    return Response.ok(uploadFileUtil.uploadFile(label, fileInputStream, fileInputDetails)).cacheControl(cc).build();
}

Error Code and Error Message

HTTP Status 400 – Bad Request

The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Answer №1

 @FormDataParam("file") InputStream uploadedFileInputStream,
 @FormDataParam("file") FormDataContentDisposition uploadedFileDetails

It appears that both the uploadedFileInputStream and uploadedFileDetails variables are being initialized from the file parameter. Additionally, in the HTML code, the field is defined as

...
Import a File: <input type="file" id="myFile" name="myfile" data-file-model="myfile"><br>

Here, the attributes id="myFile" and name="myfile" correspond to "@FormDataParam("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

Show off a font-awesome icon overlapping another image

My task involves fetching image source from a JSON file and then displaying it on an HTML page. https://i.sstatic.net/coOaU.png I also need to overlay a Font Awesome icon on top of the image as shown below: https://i.sstatic.net/nbrLk.png https://i.sst ...

Insert a numerical value into a list to make a series of numbers whole

I currently have an array of objects that looks like this: var arr = [ { "code": "10", }, { "code": "14", } ] My goal is to expand this array to contain 5 elements. The numbers should ran ...

Can a software be created to capture search results from the internet?

Is it feasible to create a program that can extract online search results? I am specifically interested in retrieving data from Some of the data I need include application numbers, such as 9078871 and 10595401 Although there are CAPTCHAs present, I am w ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

What is the best way to generate a div with a dynamically changing variable as its ID?

Creating a quiz where the user can choose how many questions to answer. A function is used to generate individual question divs based on the user's input. Each question displays a Chinese character, and the user must select the correct translation. ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

The attribute "property" is not found in the specified type of "Request<ParamsDictionary>"

Struggling to enhance the Request interface in the express package with custom properties, I keep encountering this TypeScript error: TS2339: Property '' does not exist on type 'Request<ParamsDictionary>'. Any ideas on how to re ...

Can a key event be activated on the DOM Window using Javascript or JQuery?

Can a key event be triggered on the DOMWindow or DOMDocument using JavaScript? I am developing a browser extension to interact with a website that has shortcut key events, similar to those in GMail. While I have come across other methods for triggering key ...

Is Nextjs prone to creating identical pages during the build process?

I have a question that I couldn't find the answer to anywhere, so I hope someone here can help me. I have a blog and I want to use SSG for the homepage and ISR for individual posts. If I set up my homepage using SSG to display 10 posts like this: ind ...

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

Generating JSON document by utilizing a foreach loop

I have been attempting to retrieve data from a database and then set the values in a JSON document using an ArrayList. However, I am facing challenges in doing so. Consider this hardcoded JSON that I aim to convert into dynamic JSON. String json = "{ &bso ...

Trouble looping through Javascript

Hello, I am encountering a problem with some JavaScript code that I am trying to implement. The functions in question are as follows: var changing_thumbs = new Array(); function changeThumb(index, i, thumb_count, path) { if (changing_thumbs[index]) { ...

Is there a way to stylize the initial words of a brief text block by blending small caps with italics, all while avoiding the use of a span tag?

I have a series of images with numbered captions like "Fig. 1", "Fig. 2", "Fig. 3", followed by a brief description on the same line. Is there a way to programmatically style these strings (the “Fig. #” only) using CSS or Javascript to make them italic ...

Sass is throwing an error message saying 'Module not found' during the compilation process

After installing sass using npm ($npm install sass), I attempted to create a JSON script. Unfortunately, when running it, I encountered an error stating 'Cannot find module'. ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

What is the ideal Java interface for efficiently reading and writing XML and JSON data?

In search of a user-friendly interface to convert Objects to and from their XML or JSON String representations, I have come up with the following: public interface IStringifier{ /** Converts the Object to it's String representation, e.g. XML or J ...

Tips for Making Your Popup Window Stand Out

Looking to design a unique pop-up window featuring three tree-style radio buttons and a single submit button. Upon selecting one of the radio buttons, the chosen value should be recorded in the parent window. ...

What is the process for retrieving data on the server side using node.js that has been sent from the frontend via the post method

After diving into learning node.js with the express framework, I encountered a roadblock. I'm experimenting with a basic query search webapp and trying to send some data (a boolean named all) from front-end plain javascript via ajax to the server sid ...