Как вызвать метод контроллера при загрузке файлов с помощью Angularjs Webapi

0

Я пытаюсь загрузить несколько файлов с помощью 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)

  • 0
    вы получаете файлы в объекте $scope.files ?
  • 0
    Вы указали Route как getDataForUploadFiles и вызвали objXhr.open("POST", "/file_upload"); Что явно не так.
Показать ещё 4 комментария
Теги:
asp.net-web-api2

1 ответ

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 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!");
}
  • 0
    xhr.setRequestHeader ("Content-Type", "multipart / form-data"); xhr.setRequestHeader ("X-File-Name", uf.name); не работает
  • 0
    Убедитесь, что ваш API поддерживает CORS, а авторизация - это разрешенный заголовок запроса. Когда вы отправляете запрос OPTIONS конечной точке, ваш API должен ответить следующими заголовками ответа:
Показать ещё 8 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню