简体   繁体   English

将多部分表单和JSON数据从Angular JS发送到MVC

[英]Sending Multi part form and JSON data from Angular JS to MVC

I have a upload file control that uploads the file data to a MVC Controller . 我有一个上传文件控件,可以将文件数据上传到MVC控制器。 I also want to send additional upload details model object in the same request. 我也想在同一请求中发送其他上传详细信息模型对象。

But for file - upload the request content-type undefined works for me. 但是对于文件-上传请求,内容类型未定义对我有效。 But for the MVC controller to effectively receive the model data it has to be application/json. 但是,为了使MVC控制器有效地接收模型数据,它必须是application / json。 How would I do that in a single request ? 我将如何在单个请求中做到这一点?

Or, is there any other approach I can follow ? 或者,我还有其他方法可以遵循吗? Please suggest. 请提出建议。 For the upload to complete I need both the data to be sent to the server. 为了完成上传,我需要将两个数据都发送到服务器。

I am doing is 我正在做的是

var formdata;
$scope.getTheFiles = function ($files) {
    formdata = new FormData();
    angular.forEach($files, function (value, key) {
        formdata.append(key, value);
    });

and

$scope.validateFiles = function () {

    var params = UploadDataServices.getGroupMembershipUploadParams();

    $scope.pleaseWait = { "display": "block" };

    var request = {
        method: 'POST',
        url: BasePath + 'uploadNative/ValidateFiles/',
        data: formdata,
        headers: {
            'Content-Type': undefined
        }
    };

    // SEND THE FILES.
    console.log(formdata);

    if (formdata != null || formdata != undefined) {
        $http(request)

And in the MVC controller I get the File Data as 在MVC控制器中,我得到文件数据为

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

Now I want to send that params also in the request which I got via 现在我也想通过我收到的请求发送该参数

var params = UploadDataServices.getGroupMembershipUploadParams();

How would I do that ? 我该怎么做? I tried doing 我试着做

    var request = {
        method: 'POST',
        url: BasePath + 'uploadNative/ValidateFiles/',
        data: {formdata:formdata,arg:params},
        headers: {
            'Content-Type': undefined
        }
    };

But I could not access the File Data . 但是我无法访问文件数据。

Please suggest a way . 请提出一种方法。

Thanks in advance. 提前致谢。

In this way you can upload multiple files along with some properties. 这样,您可以上传多个文件以及一些属性。

To send multiple files/records using formdata you need to use indexing on the key eg [0].someKey ie formdata.append('[' + i + '].' + key, value); 要使用formdata发送多个文件/记录,您需要在键上使用索引,例如[0].someKeyformdata.append('[' + i + '].' + key, value); but if you want to send only one record then you can remove the indexing and pass the key directly into the append function. 但是,如果您只想发送一条记录,则可以删除索引并将键直接传递给append函数。

When the user clicks on "Add File" button, then a new row is added to the table, user can select a file by clicking the file control and the directive sets the File object onto the controller's scope. 当用户单击“添加文件”按钮时,会将新行添加到表中,用户可以通过单击文件控件来选择文件,并且该指令将File对象设置为控制器的作用域。 When the "Save" button is clicked I am looping through all the files and its properties and appending them to the FormData object and posting it to the controller using a configuration object along with the FormData object. 单击“保存”按钮后,我将遍历所有文件及其属性,并将它们附加到FormData对象,然后使用配置对象和FormData对象将其发布到控制器。

The model. 该模型。

public class FileModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public HttpPostedFileBase Attachment { get; set; } // The HttpPostedFileBase provides access to files uploaded by the client.
}

The Action method on MVC Controller MVC控制器上的动作方法

[HttpPost]
public JsonResult SaveFiles(List<FileModel> files)
{
    // Your logic here.
}

The View. 风景。

<form role="form" ng-submit="saveFiles()">
    <div class="form-group">
        <table class="table table-bordered table-striped table-responsive">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>File</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-hide="files.length">
                    <td colspan="2">No records to display.</td>
                </tr>

                <tr ng-repeat="file in files">
                    <td>
                        <input type="text" class="form-control" ng-model="file.Name" />
                    </td>
                    <td>
                        <input type="file" class="form-control" file-model="file.Attachment" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="col-xs-12">
        <div class="col-xs-6">
            <button type="button" class="btn btn-info btn-sm" ng-click="addFile()">Add File</button>
        </div>
        <div class="col-xs-6">
            <button type="submit" class="btn btn-info btn-sm">Save</button>
            <button type="button" class="btn btn-info btn-sm" ng-click="cancelSaveFiles()">Cancel</button>
        </div>
    </div>
</form>

The AngularJS controller. AngularJS控制器。

var app = angular.module('example', []);

app.controller('FilesController', function ($scope) {
    $scope.files = [];
    $scope.saveFiles = saveFiles; // saveFiles func given below.
});

The AngularJS directive for <input type="file" /> . <input type="file" />的AngularJS指令。

app.directive('fileModel', function ($parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;

                element.bind('change', function () {
                    scope.$apply(function () {
                        modelSetter(scope, element[0].files[0]); // sets the file object on the model property.
                    });
                });

                scope.$watch(model, function (newValue, oldValue) {
                if (newValue === null || newValue === undefined || newValue === '') {
                    angular.element(element).val(''); // clears the file from the input element if the model is cleared.
                }
            });
        }
    };
});        

The AJAX call. AJAX调用。

function saveFiles() {
            if (angular.isArray($scope.files) && $scope.files.length > 0) {
                var formdata = new FormData();

                for (var i = 0; i < $scope.files.length; i++) {
                    for (var key in $scope.files[i]) {
                        var value = $scope.files[i][key];    
                        formdata.append('[' + i + '].' + key, value);
                    }
                }

                var config = {
                    transformRequest: angular.identity,
                    headers: { 'Content-Type': undefined }                        
                };

                $http.post('/Area/Controller/SaveFiles', formdata, config)
                    .success(saveFilesCompleted);

                function saveFilesCompleted(data) {
                    // call back
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM