Uploading multiple images using AngularJS and Spring framework

I'm encountering an issue with uploading multiple images using AngularJS and Spring MVC. While I can successfully retrieve all the files in AngularJS, when I attempt to upload them, no error is displayed, and the process does not reach the Spring controller. I simply want to output some text using a system.out.print statement. Any assistance would be greatly appreciated.

Thank you.

This is my HTML setup:

<div class="button" ngf-select ng-model="files" ngf-multiple="multiple">Select File</div>

    Drop File:
    <div ngf-drop ngf-select ng-model="files" class="drop-box"
        ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true"
        accept="image/*,application/pdf">Drop pdfs or images here or click to upload</div>
    <div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
    Files:

    <ul>
        <li ng-repeat="f in filesDetails" style="font:smaller">{{f.name}}</li>
    </ul>

</div>
</div>

<div>
         <button class="" ng-click="uploadImage()">Upload Image</button>
</div>

Here's my controller.js code:

var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('MyCtrl', ['$scope', 'Upload', '$http', function($scope, Upload, $http) {
    $scope.filesDetails = [];
    $scope.$watch('files', function() {

        $scope.upload($scope.files);
    });


    $scope.upload = function(files) {
        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {

                if (files[i].type == 'image/jpeg' || files[i].type == 'image/png') {
                    $scope.filesDetails.push(files[i]);
                } else {
                    alert("This kind of file is not Valid");

                }
            }
        }
    };

    $scope.uploadImage = function() {



        alert("uploading");
        var formData = {
            file: $scope.filesDetails
        };
        console.log(formData.file);

        var imagePost = $http.post(
            'http://localhost:8080/orion-orbit/newclue/doUpload',
            formData,
            {
                transformRequest: 
                    function(data, headersGetterFunction) {
                    return data;
                },
                headers: { 'Content-Type': 'multipart/form-data' }
            });


        imagePost.success(function(data, status,
            headers, config) {
            alert("sucess" + status);

        });
        imagePost.error(function(data, status,
            headers, config) {
            alert("Error" + status);
            alert("Exception details: " + JSON.stringify({
                data: data
            }));

        });
    }
}]);

Spring Controller setup:

@Controller</p>

@RequestMapping("/newclue")
public class ClueController {

@RequestMapping(value="/doUpload" , method = RequestMethod.POST , consumes = "multipart/form-data")

    public void handleFileUpload(@RequestParam("file") MultipartFile file) 
    {
    System.out.println("inside controller of image Upload");

    }

This is my web.xml configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Sample Spring Maven Project</display-name>
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <error-page>
        <error-code>404</error-code>
        <location>/error-pages/404-error.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error-pages/500-error.jsp</location>
    </error-page>
</web-app>

Lastly, here's my spring-config-file setup:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.orion.orbit.controller" />
    <mvc:annotation-driven />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/o2_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.orion.orbit.model.CountryCode</value>
                <value>com.orion.orbit.model.CityCode</value>
                <value>com.orion.orbit.model.ClueData</value>               
                <value>com.orion.orbit.model.ClueAns</value>
                <value>com.orion.orbit.model.AnsClueMap</value>
                <value>com.orion.orbit.model.ClueTag</value>
                <value>com.orion.orbit.model.ClueTagMap</value>
                <value>com.orion.orbit.model.NewClueRequestVO</value>
                <value>com.orion.orbit.model.UploadFile</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="simpleMappingExceptionResolver" class="com.orion.orbit.resolver.MySimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <map>
                <entry key="Exception" value="error"></entry>
            </map>
        </property>
        <property name="defaultErrorView" value="error" />
    </bean>

    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean id="clueDao" class="com.orion.orbit.dao.ClueDaoImpl"></bean>
    <bean id="clueServices" class="com.orion.orbit.services.ClueServicesImpl"></bean>
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="10000000" />
    </bean>
    <mvc:resources mapping="/resources/**" location="/resources/" />

</beans>

Answer №1

There are several key factors to consider.

  1. Based on the URL provided, it appears that your root context is orion-orbit, 'http://localhost:8080/orion-orbit/newclue/doUpload', Therefore, you need to map your requestMapping to @RequestMapping(value="/newclue/doUpload"

  2. The way URLs are mapped also plays a role. Verify your web.xml configuration for the request dispatcher and any URL redirections.

  3. Additionally, ensure that you have a Spring multipart resolver bean defined in your applicationContext.xml to handle multipart uploads.

For example:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

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

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

Paragraph Separated by Bullets Without Bullets At End of Line

I need assistance in creating a unique type of list that I call a "bullet separated paragraph list" by using a javascript array of strings. For example: item • item • item • item • item     item • item • item • item item • ...

Obtaining information from an AngularJS Service Response and assigning it to the Controller Scope Object

I have a basic AngularJS 1.7 application where I am successfully fetching data from a web API using an AngularJS service. However, I am running into an issue where the data is not being populated in the controller scope object. I have verified that the dat ...

Should the page.js in a Next.js App router be a server component?

Is it standard practice in Next.js 13 and above (App router) for the page.js of all routes/folders to be a server component? I know that it can be a client component with use client, but is this advisable or are there potential issues during the build proc ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

Tips for creating an infinite repeating loop in jQuery

I'm attempting to create a jQuery infinite loop featuring images within a div. I've experimented with using the setInterval function, but encountered an issue where the animation starts after a 3-second delay and does not seamlessly repeat itself ...

Investigate duplicate elements within nested arrays using the 3D array concept

I am dealing with an array that contains 3 subarrays. Arr = [[arr1],[arr2],[arr3]] My task is to identify and store the duplicate values found in these subarrays ([arr1],[arr2],[arr3]) into a separate array. Arr2 = [ Duplicate values of arr 1,2,,3 ] What ...

LeadFoot's intern framework encountered difficulty locating an element

I am currently in the process of writing functional test cases using the leadfoot intern framework. The specific test case I am working on involves entering text into a form field and clicking a button that triggers the opening of a bootstrap modal. My goa ...

In search of a comprehensive AJAX-enabled content management system

Is there a Content Management System (CMS) available that can create a fully ajax-driven website, allowing for a persistent Flash component without the need to reload it with each page navigation? ...

populate vueJS table with data

I encountered an issue while trying to load data from the database into my table created in VueJS. I have set up my component table and my script in app.js, but I am seeing the following error in the view: [Vue warn]: Property or method "datosUsuario" ...

Is there a way to ensure the content of two divs remains aligned despite changing data within them?

Currently, I have two separate Divs - one displaying temperature data and the other showing humidity levels. <div class="weatherwrap"> <div class="tempwrap" title="Current Temperature"> ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Efficient Ways to Present and Personalize Indian Date and Time using JavaScript

Hey there, currently creating my website and need some assistance. I'm looking to display the date and time in different sections of the page. Having some trouble with getting Indian time to work properly using PHP. If you could help me out with Ja ...

Issues with Access-Control-Allow-Origin in .NET Core Deployment on IIS Set up on Windows Server 2016

I have checked various sources like Microsoft Documentation, SO Answers, and even installed IIS CORS module, but I am still struggling to get it right. The issue arises with my .NET Core API 3.1 hosted on IIS at AWS EC2 Windows Server 2016 datacenter, acc ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Having trouble accessing data from MongoDB using Node.js and Express

Looking to retrieve data from Mongo DB using Node JS and Express JS? After creating a mongoose schema and exporting the module, you may encounter an issue where running the function returns an empty JSON object. Take a look at the code snippets below: Thi ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

Is there a way to trigger an Ajax function after individually selecting each checkbox in a list in MVC 4 using Razor syntax?

Is it possible to trigger an AJAX function when a checkbox within the ul below is checked? Each checkbox has a unique name attribute, such as chkbrand_1, chkbrand_2, chkbrand_3, etc. I am able to obtain the correct value using this code: $('.sear ...