Using AngularJS and SpringMVC for uploading multiple files at once

Having recently delved into the world of angularJS, I've been attempting to upload a file using angular JS and Spring MVC. However, despite my efforts, I have not been able to find a solution and keep encountering exceptions in the JS Controller.

Below is the code snippet that I've been working on. Take a look and any help would be greatly appreciated. Thank you!

ApplicationContext.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000" /> <!-- setting maximum upload size -->
</bean>

JSP:

<div data-ng-controller='QuestionController'>
<form name="createChapForm" data-ng-submit="submitQue();" enctype="multipart/form-data" class="form-horizontal">
    <div class="form-group">
        <label class="control-label col-sm-3">Select Class * :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='class_id' data-ng-init='getClasses();' data-ng-change='getSubjectsClasswise(class_id);' class="form-control" required>
                    <option value="">--SELECT--</option>
                    <option data-ng-repeat='c in clss' value="{{ c.class_id}}">{{ c.class_name}}</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-3">Select Subject * :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='question.sid' data-ng-change='doGetChapters(question.sid);' class="form-control" required>
                    <option value="">--SELECT--</option>
                    <option data-ng-repeat='s in subsss' value="{{ s.sid}}">{{ s.subject_name}}</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-3">Select Chapter :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='question.chap_id' class="form-control" >
                    <option value="">ALL</option>
                    <option data-ng-repeat='c in chapters' value="{{ c.chap_id}}">{{ c.chap_name}}</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="control-label col-sm-2" >Question :</div>
        <div class="col-sm-10 padding_0">
            <textarea data-ng-model='question.question_text' rows="5" class="form-control  " > </textarea>
            <div class="right">
                <div class="fileUpload btn btn-primary1 btn-sm">
                    <input type="file" data-ng-model="file" name="file" id="file"  id="q_id"  class="upload" />
                </div>
            </div>
        </div>
    </div>
</form>
</div>

AngularJS Controller:

$scope.submitQue = function() {
    console.log('file is ' ); console.dir(file.files[0]);
    var URL =appURL+'/adm/doAddQuestion.do';
    var fd = new FormData();
    fd.append('file', file.files[0]);
    fd.append('questionBean', angular.toJson($scope.question, true));
    $http.post(URL, fd, {
        transformRequest : angular.identity,
        headers : {
            'Content-Type' : undefined
        }
    }).success(function() {
        console.log('success');
    }).error(function() {
        console.log('error');
    });
}

Java Controller:

@RequestMapping(value = "/doAddQuestion.do", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseBody String saveUserDataAndFile(@RequestParam(value = "file") MultipartFile file, @RequestBody QuestionBean questionBean) {
    System.out.println("output: "+questionBean.getQuestion_text());
    // Im Still wotking on it
    return "";
}

Exceptions:

Mar 08, 2017 7:46:46 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
WARNING: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]
Mar 08, 2017 7:46:46 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver logException
WARNING: Handler execution resulted in exception: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]

Answer №1

Include these JavaScript files along with your existing angular.js files: angular-file-upload.js,angular-file-upload-shim.js,ng-file-upload.js,ng-file-upload-shim.js

You can download the necessary files from this link: Angular File For Upload.

Add ngFileUpload,'angularFileUpload' to your angular.module as shown below:

angular.module('formSubmit', [ 'ngFileUpload',
            'angularFileUpload',  'ui.router' ]);

Next, add $upload to your Angular controller like so:

app.controller('FormSubmitController', function($scope, $http, $upload)

Replace $http.post with $upload.upload in your Angular code:

$upload.upload({
    url : 'doAddQuestion.do',
    file : yourFile,
    data : $scope.questionBean,
    method : 'POST'
});

Update your Spring controller accordingly:

@RequestMapping(value = "/doAddQuestion.do", method = RequestMethod.POST, headers = ("content-type=multipart/*"))
public @ResponseBody String saveUserDataAndFile(@RequestParam("file") MultipartFile file, QuestionBean questionBean) {
    System.out.println("output: "+questionBean.getQuestion_text());
            // Work in progress
    return "";
}

Answer №2

Make sure to update your request mapping by including the code snippet below:

 @RequestMapping(value = "/upload-file", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

This adjustment will eliminate any multipart exceptions in your application.

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

Welcome to the JavaScript NodeJs Open Library!

I am trying to open multiple images simultaneously in the default Windows Photo Viewer that I have stored in my folder using the npm open library: let files = ['Dog.gif', 'Cat.jpeg']; for(let i=0; i<files.length; i++){ open(`${file ...

The art of replacing material-ui styles with styled components

As a newcomer to UI material design, I am eager to create my own customized Button Component using styled-components. I am facing a challenge in overriding the CSS based on different button variations such as "primary" or "secondary". You can find my cod ...

Troubleshooting the "Failed to mount component" error in Vue: fixing template or render function definition issues

Struggling with writing a Vue component, encountering the issue: Failed to mount component: template or render function not defined. Tried various fixes like adding default when importing the component, but none of them seem to work. My component code is i ...

Is there a universal method to disregard opacity when utilizing jQuery's clone() function across different web browsers?

I've encountered a situation where I need to allow users to submit a new item to a list within a table, and have it smoothly appear at the top of the list. While using DIVs would make this task easier, I am working with tables for now. To achieve thi ...

Unable to add a string to a http get request in Angular

When a specific ID is typed into the input field, it will be saved as searchText: <form class="input-group" ng-submit="getMainData()"> <input type="text" class="form-control" ng-model="searchText" placeholder=" Type KvK-nummer and Press Enter" ...

Understanding the functionality of app.listen() and app.get() in the context of Express and Hapi

What is the best way to use only native modules in Node.js to recreate functionalities similar to app.listen() and app.get() using http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype.get = function(call ...

Retrieve the array element that is larger than the specified number, along with its adjacent index

Consider the following object: const myObject = { 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, }; Suppose we also have a number, let's say 25. Now, I want to iterate over the myObject using Object.entries(myObject), and obtain a specific result. For ...

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Having trouble with retrieving JSONP data? Unsure how to access the information?

Why do I keep getting a -403 error? https://i.stack.imgur.com/T53O9.png However, when I click on the link, I see this: https://i.stack.imgur.com/8GiMo.png How can I retrieve the message? ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

Utilizing functions as arguments in AngularJS 1.5 directives

app.controller('myController', [ '$scope', function ( $scope ) { $scope.doSum = function(x, y){ console.log(x+y); }; } ]); <cmp data-fn="doSum(x, y)"></cmp> app.directive('cmp&apo ...

Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the ...

Stop the page from automatically scrolling to the top when the background changes

Recently, I've been experimenting with multiple div layers that have background images. I figured out a way to change the background image using the following code snippet: $("#button").click(function() { $('#div1').css("background-image ...

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Ensuring Angular applications can effectively run on Internet Explorer

In my Angular application, I have implemented the functionality where users can choose a map to select the delivery point for goods. However, there seems to be an issue with this feature in Internet Explorer (IE) - the map opens but the delivery points ar ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Gatsby Dazzling Graphic

I'm currently facing an issue with my Heroes component. const UniqueHero = styled.div` display: flex; flex-direction: column; justify-content: flex-end; background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${prop ...

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...