如何使用Angularjs Webapi调用文件上载中的控制器方法

时间:2016-07-28 09:25:57

标签: c# angularjs asp.net-web-api2

我正在尝试使用Angularjs和webapi上传多个文件。 这是我的html表:

<body ng-app="fupApp">

    <div ng-controller="fupController">
        <input type="file" id="file" name="file" multiple
               onchange="angular.element(this).scope().getFileDetails(this)" />

        <input type="button" ng-click="uploadFiles()" value="Upload" />

        <!--ADD A PROGRESS BAR ELEMENT.-->
        <p><progress id="pro" value="0"></progress></p>
    </div>

</body>

这是我的Angularjs代码,用于多文件上传(fileupload.js):

var myApp = angular.module('fupApp', []);

myApp.controller('fupController', function ($scope) {

    // GET THE FILE INFORMATION.
    $scope.getFileDetails = function (e) {
        debugger;
        $scope.files = [];
        $scope.$apply(function () {
            debugger;
            // STORE THE FILE OBJECT IN AN ARRAY.
            for (var i = 0; i < e.files.length; i++) {
                $scope.files.push(e.files[i])
            }

        });
    };

    // NOW UPLOAD THE FILES.
    $scope.uploadFiles = function () {
        debugger;
        //FILL FormData WITH FILE DETAILS.
        var data = new FormData();

        for (var i in $scope.files) {
            data.append("uploadedFile", $scope.files[i]);
        }

        // ADD LISTENERS.
        var objXhr = new XMLHttpRequest();
        objXhr.addEventListener("progress", updateProgress, false);
        objXhr.addEventListener("load", transferComplete, false);

        // SEND FILE DETAILS TO THE API.
       objXhr.open("POST","MailRoute/getDataForUploadFiles");

        objXhr.send(data);
    }

    // UPDATE PROGRESS BAR.
    function updateProgress(e) {
        debugger;
        if (e.lengthComputable) {
            document.getElementById('pro').setAttribute('value', e.loaded);
            document.getElementById('pro').setAttribute('max', e.total);
        }
    }

    // CONFIRMATION.
    function transferComplete(e) {
        debugger;
        alert("Files uploaded successfully.");
    }
});

这是我在webapi中的功能:

 public async Task<HttpResponseMessage> getDataForUploadFiles()
                {
                 }

但如何读取文件deatils并从控制器方法访问文件详细信息(getDataForUploadFiles)

1 个答案:

答案 0 :(得分:0)

试试这个

  <div ng-controller="Ctrl">
    <input type="file" file-upload multiple/>
    <ul>
        <li ng-repeat="file in files">{{file.name}}</li>
    </ul>
  </div>

控制器代码

function Ctrl($scope, $http) {

    //a simple model to bind to and send to the server
    $scope.model = {
        name: "",
        comments: ""
    };

    //an array of files selected
    $scope.files = [];

    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });
    });

    //the save method
    $scope.save = function() {
        $http({
            method: 'POST',
            url: "/MailRoute/getDataForUploadFiles",
            //IMPORTANT!!! You might think this should be set to 'multipart/form-data' 

            headers: { 'Content-Type': false },

            transformRequest: function (data) {
                var formData = new FormData();

                formData.append("model", angular.toJson(data.model));
                //now add all of the assigned files
                for (var i = 0; i < data.files; i++) {
                    //add each file to the form data and iteratively name them
                    formData.append("file" + i, data.files[i]);
                }
                return formData;
            },
            //Create an object that contains the model and files which will be transformed
            // in the above transformRequest method
            data: { model: $scope.model, files: $scope.files }
        }).
        success(function (data, status, headers, config) {
            alert("success!");
        }).
        error(function (data, status, headers, config) {
            alert("failed!");
        });
    };
};

处理数据服务器端

public async Task<HttpResponseMessage> getDataForUploadFiles()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var root = HttpContext.Current.Server.MapPath("~/App_Data/Temp/FileUploads");
    Directory.CreateDirectory(root);
    var provider = new MultipartFormDataStreamProvider(root);
    var result = await Request.Content.ReadAsMultipartAsync(provider);
    if (result.FormData["model"] == null)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    var model = result.FormData["model"];
    //TODO: Do something with the json model which is currently a string



    //get the files
    foreach (var file in result.FileData)
    {                
        //TODO: Do something with each uploaded file
    }

    return Request.CreateResponse(HttpStatusCode.OK, "success!");
}