如何使用angularjs将文件详细信息发送到后端?

时间:2017-08-04 11:47:16

标签: javascript angularjs

您好我正在开发angularjs中的Web应用程序。我正在开发文件上传模块。我在数组下面有文件详细信息。

//在代码下方获取文件数组

$scope.showPicker=function()
            {
                var client = filestack.init('AGeDIRvVZTRWgtmFbfGuZz');
                client.pick({
                }).then(function (result) {
                    arrMakes.push(result.filesUploaded);
                });
            }

FileDetails(array)

在上图中我展示了我的阵列。我有三个文件。 下面是我将详细信息发送到api的角度代码。

var files = new FormData();

angular.forEach(arrMakes, function (value, index) {
  console.log(value,index);
  files.append(index, value);
  files.append('data', angular.toJson(index).replace(/['"]+/g, ''));
});

return $http.post(this.uploadUrl, files, {
  transformRequest: angular.identity,
  headers: {
    'Content-Type': undefined,
  }
})

问题是我没有在服务器端接收文件。下面的行给出了服务器中的0个文件。

System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

我知道我是否正在向服务器发送正确的数据?有人可以帮我解决这个问题吗?任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

You are not uploading any files to the server, only strings.

You can't append objects to a FormData. appart from Blob & File objects
See what will happen:

fd = new FormData
fd.append(2, {foo: 'bar'})
fd.append('data', 5)
new Response(fd).text().then(console.log)
// you get [object Object]

Why do you stringify the index in "data"? It will be casted to string automatically. And what is there that you have to replace?

If i where you i would just simple send the hole arrMakes to the server and download all the files from the url on the backend, otherwise the client has to download and then upload them to the server and wasting bandwidth and time.

beside, you don't need angulars forEach loop, arrays has that method built in

arrMakes.forEach(function (value, index) {
  ...
})

You won't even have to use any loop if you just pass the arrMarks to the server