0

I use angularjs in my project.

I laod file with extension .xlsx and I need to post it to the web services and two integers numbers, month and year.

Here is HTML:

    <div class="col-xs-5">
        <label class="btn btn-success btn-sm">
            Load File <input type="file" id="inptFile" onchange="$('#upload-file-info').html(this.files[0].name)" hidden>
        </label>
        <span class='label label-default' id="upload-file-info">. . .</span>
    </div>

Here is javascript code that fired after the file is loaded:

       $scope.loadFile = function () {
        if (hasExtension('inptFile', ['.xlsx'])) 
        {
             var file = $('#inptFile')[0].files[0]; //get the file  
            //here post file to service.
        }
        else {}
    }

    function hasExtension(inputID, exts) {
        var fileName = document.getElementById(inputID).value;
        return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName);
    }

And here is web service:

    [WebMethod]
    public List<DepartmentReport> SaveXml(int year, int month, file)
    {
        //some logic
    }

After I get the file(after this row) var file = $('#inptFile')[0].files[0] I need to post file, year and month to web service.

How can I post two integers and file to the web service above using angularjs $http post?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • I use [ng-file-upload](https://github.com/danialfarid/ng-file-upload). It's pretty easy to use and the documentation is good. – Mickers Dec 12 '17 at 15:15

1 Answers1

2

With your backend, you can handle your file upload like this :

@PostMapping("/{year}/{month}")
public ResponseEntity<List<DepartmentReport>> saveXml(@PathVariable("year") Integer year,
    @PathVariable("month") Integer month
    @RequestParam("file") MultipartFile file) {

    // TODO

}

Explanation

You can handle both the file and the parameters using PathVariable annotation. It will define a REST URL for your uplaod like this : <endpoint>/2017/12.

You can also use RequestParam annotation instead of PathVariable. It will change your URL to something like this <endpoint>?year=2017&month=12.

IMO, the first option looks better.

With AngularJS, you can handle the file upload like this :

$http({
    method: 'POST',
    url: '<endpoint>/' + year + '/' + month,
    headers: {
        'Content-Type': 'multipart/form-data'
    },
    data: $scope.file
})
.success(function (data) {

})
.error(function (data, status) {

});

Please note that I didn't test any of this but I hope this will help you.

Documentation :

Mickael
  • 4,458
  • 2
  • 28
  • 40