Using angularjs 1.3 and C# .net core web api
I have a ng-file-upload which being used to upload file. When the upload method is called I want to pass in an extra array of some data to the upload method which is then received by the method at my web api. Here is my ng-file-upload
factory.upload = function (file, myArray) {
var url = '{0}upload'.format(apiPath)
return Upload.upload({
url: url,
arrayKey: '',
data: { file: file, myArray: myArray}
}).then(function (res) {
return res;
});
};
Below is my webapi:
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file, List<string> myArray)
{
//code
}
And finally here is the array which I am trying to pass along with upload to my webapi:
[
{
id: "1",
name: "steve"
},
{
id: "2",
name: "adam"
}
]
The issue is in my webapi, the myArray parameter which is to accept the array from the UI is always null. I searched online and its mentioned to add
arrayKey: ''
But still doesnt works. Any inputs?
---Updated---
I created a string array as :
var cars = ["steve", "adam", "ronnie"];
And updated my api as:
List<ArrayItem> myArray
The above code works. So looks like there is issue with array being passed. I am passing the following array by creating like this:
var myArray= [];
for (var i = 0; i < myJson.length; i++) {
myArray.push({
id: myJson[i].id,
name: myJson[i].name,
});
}
The result of above as seen in console:
Array(2)
0:{id: "1", name: "steve"}
1:{id: "2", name: "adam"}
Whats missing here?
For passing object array, you need to define the list object to accept the parameters.
ArrayItem with Id
/Name
properties.
public class ArrayItem
{
public int Id { get; set; }
public string Name { get; set; }
}
Change action
public async Task<IActionResult> FileUpload(IFormFile file, List<ArrayItem> myArray)
{
return Ok();
}
Update
You need to remove arrayKey: '[]'
, try code below:
app.service('crudService', function ($http, Upload) {
var baseUrl = 'http://localhost:50829';
this.uploadFile = function (file, array) {
return Upload.upload({
url: baseUrl + "/api/books/file/upload",
//arrayKey: '[]',
data: { file: file, array: array },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (res) {
return res;
}, function (err) {
throw err;
});
};
});