Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature.

var fileInput = document.getElementById('jquery-ajax-single')
    var form = new FormData();
    form.append('uploadFile',fileInput.files[0]);

    $.ajax({
        url: "file/upload",
        processData : false,
        contentType : false,
        data : form,
        type : 'POST',
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
                console.log(Math.floor(e.loaded / e.total *100) + '%');
                $('#progress-jquery-ajax-single.progress-bar-progress').css(
                        'width', Math.floor(e.loaded / e.total * 400)+ 'px'
                );
            };
           return xhr;
        }
    });

The above code is functional and successfully directs to the FileController.

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
    public void upload(@RequestParam MultipartFile uploadFile){


        System.out.println("name : " + uploadFile.getOriginalFilename());
        System.out.println("content-type : " + uploadFile.getContentType());
        System.out.println("size : " + uploadFile.getSize());
    }
}

After each ajax process, the upload progress is displayed. Once it reaches 100%, it goes to the FileController and displays the file information. However, checking the Chrome browser console shows:

jquery-2.1.4.js:8630 POST http://localhost:8080/FileUploadWeb/file/upload 404 (Not Found).

I also attempted using dropzone.js, which resulted in the same error 404 but modified the URL to http://localhost:8080/FileUploadWeb/file/file/upload

<form id="my-dropzone"action="file/upload" class="dropzone"></form>

Answer №1

While researching, I came across this resource, which suggested that the solution to my issue was to include a ResponseBody entity in the POST method:

@PostMapping(value = "/upload")
public ResponseEntity<String> upload(@RequestParam MultipartFile uploadFile) {
    System.out.println("name : " + uploadFile.getOriginalFilename());
    System.out.println("content-type : " + uploadFile.getContentType());
    System.out.println("size : " + uploadFile.getSize());

    return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}

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

Retrieving QueryString from Request or JavaScript

On my aspx page, I am dealing with a query string - www.mysite.com/enter.aspx?dest=#. After clicking "enter," the page navigates to main.aspx. I am looking for a way to extract this "?dest=#" from the query string in main.aspx using either request.querystr ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

Toggle button to collapse the Bootstrap side bar on larger screens

I am currently utilizing the following template: An issue I am facing is that I want my sidebar to either shrink or hide when a button is clicked, specifically on a 22" PC screen. I have experimented with several solutions without achieving success. Alt ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

Tips for updating process.version in a Node.js environment

After upgrading my node version from v3 to v11 using nvm with the command nvm use 11.12.0, I noticed that when I check the version using node -v in the terminal, it correctly shows 11.12.0. I also have a node js application that is started through pm2. I ...

How to include an href in a button using Pug without disrupting a form

Is there a way to create a button that redirects to my /leaderboard page once my quiz app submits? h1 Play Time 4 Trivia! button Go form(method='POST') ul each val in questions li ...

Unable to retrieve information using ajax in a codeigniter framework

I'm trying to display the restaurant information after selecting its area from a dropdown list. However, my code is not showing the restaurant name and the menu button for that restaurant. Can you please point out where I made a mistake? This is my m ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Using Model-View-Controller (MVC) to seamlessly integrate jQuery with AJAX for dropdown lists and

Here's the scenario: When a user selects a category from a dropdown on the page, the second dropdown next to it should dynamically populate with all users in that category. I'm using LinqtoSQL to retrieve all the data and I have a couple of ques ...

The website appears to be loading in a unique way on mobile upon the second loading

While developing my personal website, I encountered a bug that occurs when accessing the site on my Android phone using Firefox or Chrome. The issue arises when the page initially loads correctly, but upon refreshing, the layout is displayed differently. ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

How can we use PHP and jQuery to open a simple modal with data?

Here is a basic modal setup: <div id="info" style="display: none;"> <h3 class="title">User Information</h3> <table border="0" cellpadding="5" cellspacing="0"> <tr> <td width="50%" align="right ...

Calculating Dynamic Values in CodeIgniter through jQuery

Here's the JavaScript code I'm working with: $('#type').on('change', function() { var id = $("#type").val(); user_id = $("#user").val(); var jqxhr = $.ajax({ type: "POST", url: "<?php echo base_ ...

Using Restify to Serve CSS FilesLearn how to use Restify to

Currently, I am developing a node application that requires serving static files like JavaScript and CSS. In my project structure, I have the following layout: -MyProject -backend -index.js -frontEnd -index.html -js ...

Pass information from one .jsp file to a JavaScript function in another .jsp file

Here is the content of OneEmployee.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <form> <td> <c:out value="${emp.getEmpid()}"/></td> <td> <input type="text" id="fname" value="<c:out v ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Guide on leveraging npm start to compile ES6 React components and Foundation Sass

Following a tutorial on setting up a React project, everything seemed to be working perfectly after installation. However, I now need to incorporate Foundation as the front-end library for a website. The issue arises because the tutorial's server.js ...

Ensure to verify the values of two variables when using a switch case statement

I'm working with two variables that can return true or false. My goal is to display a corresponding text message for each variable if it returns false. How can I effectively handle the ValidCheked and repeatChecked variables in a switch statement? ...