带有表单数据和参数的AngularJS AJAX发布

时间:2019-01-28 18:00:26

标签: angularjs ajax

我是AJAX的新手,所以我不知道这是否是一个好习惯。

我想使用AngularJS在Form Data中使用二进制文件数据以及一个附加对象作为参数来进行发布。这是我的JS:

var files = document.getElementById('txtUploadFile').files;
        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }

                $http({
                    method: 'POST',
                    url: ghostApp.VirtualFolder + "/AggregatorArea/AggregatorArea/UploadBOL",
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    transformRequest: function(obj) {
                        var str = [];
                        for(var p in obj)
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        return str.join("&");
                    },
                    data: data,
                    params: { purchaseOrderHeader: $scope.purchaseOrderHeader }
                }).success(function (result) {
                    $("#ajax_loader").hide();
                    $scope.pagemodel.uploadMessage = result;
                    if (result == "BOL Uploaded Successfully.") {
                        setTimeout(function () { window.location.reload(); }, 5000);
                    } else {
                        $scope.pagemodel.enableFileText = true;
                    }
                    console.log(result);
                }).error(function (error) {
                    $("#ajax_loader").hide();
                    console.log(error);
                    $scope.pagemodel.uploadMessage = "ERROR";
                });
                ...

这是我的控制器:

public ActionResult UploadBOL(PurchaseOrderHeader purchaseOrderHeader)
        {
            string gtfile = "Upload BOL Error";
            byte[] data = null;
            try
            {
                foreach (string file in this.Request.Files)
                {
                    var hpf = this.Request.Files[file];
                    if (hpf != null)
                    {
                        var getpath = hpf.FileName;
                        MemoryStream target = new MemoryStream();
                        hpf.InputStream.CopyTo(target);
                        var extension = Path.GetExtension(getpath);
                        if (extension == ".pdf")
                        {
                            data = target.ToArray();

                            string output = _objBusiness.SaveUploadedFile(data, SessionWrapper.UserId, CommonConstants.unsigned, purchaseOrderHeader);
...

我一直在尝试各种参数的组合和排列,但是我无法同时获取文件数据和参数数据。

0 个答案:

没有答案