1

I am new to angularJS and trying to upload a file using angular JS and Spring MVC, but not able to get the required solution and ending up with exceptions in JS Controller.

Below is the code, Have a look and please help me out. 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]
5
  • Your error is clear Expected MultipartHttpServletRequest: is a MultipartResolver configured? @see Multipart Resolver Commented Mar 8, 2017 at 13:35
  • @EddieB changed but still giving the same exception Commented Mar 8, 2017 at 13:59
  • 'Changed' ? You need to configure a multipart resolver... @more info Configure Multipart Resolver Commented Mar 8, 2017 at 14:03
  • @EddieB updated the changes, please have a look Commented Mar 8, 2017 at 14:25
  • Your original issue. multipart resolver is resolved. You need to follow the SO rules and post a new question for the new problem Commented Mar 8, 2017 at 14:41

2 Answers 2

2

Add these .js file where you have added angular.js files angular-file-upload.js,angular-file-upload-shim.js,ng-file-upload.js,ng-file-upload-shim.js

You can download from this link Angular File For Upload.

Then Add ngFileUpload,'angularFileUpload' in angular.module see below line.

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

Then Add $upload in your angular controller like this.

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

Use $upload.upload instead of $http.post in your angular code.

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

Change your spring controller.

@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());
            // Im Still wotking on it
    return "";
}
Sign up to request clarification or add additional context in comments.

5 Comments

what is this yourFile?
In your case you have to replace with this code file.files[0]
showing error in console Error: [$injector:unpr] Unknown provider: $uploadProvider <- $upload
I have edited my answer please follow all the steps.
I used the exact files and suggested controller parameter list. I am getting a 400 (Bad Request) Any suggestions why that is?
0

update your request mapping with the following code:

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

It will remove your multipart exception.

5 Comments

changed but still giving the same exception
I think your multipart exception is been resolved now, the current issue is might be in your request object now.
no.. now its giving some different exception.. i updated the question, have a look
"QuestionBean" is your entity class? if yes then implements Serializable, as suugested in this link: stackoverflow.com/questions/34888326/…. Let me know if it works for you
@hrdkisback - I am trying the same exact functionality you mentioned above in answer..Even i'm facing the error. It is showing error in console Error: [$injector:unpr] Unknown provider: $uploadProvider <- $upload..i followed all the steps you metioned in the answer..Any inputs?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.