文件上传:将数组发送到Web Api

问题描述 投票:0回答:1

使用angularjs 1.3和C#.net核心web api

我有一个用于上传文件的ng-file-upload。当调用upload方法时,我想将一些额外的数据数组传递给upload方法,然后由我的web api方法接收。这是我的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;
    });
};

以下是我的webapi:

  [HttpPost("upload")]
   public async Task<IActionResult> FileUpload(IFormFile file, List<string> myArray)
   {
        //code
   }

最后这里是我试图传递的数组上传到我的webapi:

  [
   {
     id: "1",
     name: "steve"
   },
   {
     id: "2",
     name: "adam"
   }
  ]

问题出在我的web api中,从UI接受数组的myArray参数始终为null。我在网上搜索并提到要添加

 arrayKey: '' 

但仍然不起作用。有什么投入?

- -更新 - -

我创建了一个字符串数组:

var cars = ["steve", "adam", "ronnie"];

并将我的api更新为:

List<ArrayItem> myArray

上面的代码有效。所以看起来传递数组存在问题。我通过这样创建传递以下数组:

  var myArray= [];
  for (var i = 0; i < myJson.length; i++) {
   myArray.push({
    id: myJson[i].id,
    name: myJson[i].name,
  });                                        
 }  

上面的结果如控制台中所示:

Array(2)
0:{id: "1", name: "steve"}
1:{id: "2", name: "adam"}

什么不见​​了?

angularjs json asp.net-web-api asp.net-core-webapi ng-file-upload
1个回答
1
投票

对于传递对象数组,您需要定义列表对象以接受参数。

  1. 具有Id / Name属性的ArrayItem。 public class ArrayItem { public int Id { get; set; } public string Name { get; set; } }
  2. 改变行动 public async Task<IActionResult> FileUpload(IFormFile file, List<ArrayItem> myArray) { return Ok(); }

更新

您需要删除arrayKey: '[]',请尝试以下代码:

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;
    });
}; 
});
© www.soinside.com 2019 - 2024. All rights reserved.