簡體   English   中英

將多部分表單和JSON數據從Angular JS發送到MVC

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

我有一個上傳文件控件,可以將文件數據上傳到MVC控制器。 我也想在同一請求中發送其他上傳詳細信息模型對象。

但是對於文件-上傳請求,內容類型未定義對我有效。 但是,為了使MVC控制器有效地接收模型數據,它必須是application / json。 我將如何在單個請求中做到這一點?

或者,我還有其他方法可以遵循嗎? 請提出建議。 為了完成上傳,我需要將兩個數據都發送到服務器。

我正在做的是

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

$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)

在MVC控制器中,我得到文件數據為

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

現在我也想通過我收到的請求發送該參數

var params = UploadDataServices.getGroupMembershipUploadParams();

我該怎么做? 我試着做

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

但是我無法訪問文件數據。

請提出一種方法。

提前致謝。

這樣,您可以上傳多個文件以及一些屬性。

要使用formdata發送多個文件/記錄,您需要在鍵上使用索引,例如[0].someKeyformdata.append('[' + i + '].' + key, value); 但是,如果您只想發送一條記錄,則可以刪除索引並將鍵直接傳遞給append函數。

當用戶單擊“添加文件”按鈕時,會將新行添加到表中,用戶可以通過單擊文件控件來選擇文件,並且該指令將File對象設置為控制器的作用域。 單擊“保存”按鈕后,我將遍歷所有文件及其屬性,並將它們附加到FormData對象,然后使用配置對象和FormData對象將其發布到控制器。

該模型。

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.
}

MVC控制器上的動作方法

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

風景。

<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>

AngularJS控制器。

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

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

<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.
                }
            });
        }
    };
});        

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