简体   繁体   中英

sending file from angularjs controller to spring controller showing bad request 404

m trying to fetch the files from Angularjscontroller to Spring Controller to upload the excel file from angular and read from spring controller

this is AngularController Code

 'use strict';
  webapp.directive('fileModel', ['$parse', function ($parse) {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
                });
        });
    }
};
}]);
       webapp.service('fileUpload', ['$http', function ($http) {
     this.uploadFileToUrl = function(file, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .success(function(fd){
        alert(sucess+fd)
    })
    .error(function(fd){
        alert(error+fd)
    });
}
    }]);
    webapp.controller('bussinesscontroller', ['$scope', 'fileUpload',    function($scope, fileUpload){
    $scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log('file is ' );
    console.dir(file);
    var uploadUrl = '/uploadsfiles';
    fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);

this is spring controller Code

   @RequestMapping(value="/uploadsfiles",method=RequestMethod.POST)
  @ResponseBody
   public JSONObject getFile(@RequestParam("file") String file ){
    JSONObject jsonObject=new JSONObject();

    /*System.out.println("data= "+data);*/
    System.out.println("hiii...");

    return jsonObject;
    }

this is html code

<body>
<div ng-controller="bussinesscontroller">
<fieldset>
 <!-- <form name="fileupload"   novalidate> -->
<legend>Excel File upload</legend>
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload</button>      
 </fieldset>
 <!-- </form> -->
 </div>
  </body>
  </html>

Hi @rohit look I'm not familiar with Angular, but I know enough about Spring to tell you that your problem is in its configuration. First of all you have to declare a filter in your web.xml to let know Spring MVC that your are trying to use its FileUpload feature:

<filter>
    <filter-name>springMultipartFilter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>springMultipartFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Next step is configure what is the limit in bytes, if you want to do it (I recommend you to use it for security and performance matters). Add this bean in your spring-servlet.xml:

<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1048576"/>
</bean>

Finally add the file upload dependency to the Maven configuration, or add the library if not using Maven:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

Now, what you have to do in your code is create a simple form bean with the multipart file:

import org.springframework.web.multipart.MultipartFile;    

public class MyAngularSpreadSheetForm {

    private MultipartFile spreadSheetFile;

    public MultipartFile getSpreadSheetFile() {
        return spreadsheetFile;
    }

    public void setSpreadSheetFile(MultipartFile spreadsheetFile) {
        this.spreadsheetFile = spreadsheetFile;
    }

}

Now configure your Controller to create this form object in the GET method that displays your HTML form in Angular and another POST method that receives this object when you trigger the submit button:

@Controller
public class MyAngularController {

    @RequestMapping(value = "/displayUploadsfiles", method = RequestMethod.GET)
    public String display(ModelMap context) {

        context.addAttribute("myFile", new MyAngularSpreadSheetForm());

        return "myAngularPage";
    }

    @ResponseBody
    @RequestMapping(value="/uploadsfiles",method=RequestMethod.POST)
    public JSONObject getFile(@ModelAttribute MyAngularSpreadSheetForm myFile){

        MultipartFile multipartFile = myFile.getSpreadSheetFile();

        if (multipartFile != null) {
            String originalFilename = multipartFile.getOriginalFilename();
            Long fileSize = multipartFile.getSize();

            File tempFile = null;

            try {
                InputStream inputStream = multipartFile.getInputStream();
                // here goes your file manipulation instructions if you want to use Apache POI or Jxl or another API that manipulates spread sheets
            } catch (Exception exception) {
                // here goes the way how you control your error and display it in the view
            }
        }

        JSONObject jsonObject=new JSONObject();

        /*System.out.println("data= "+data);*/
        System.out.println("hiii...");

        return jsonObject;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM