0

i am trying to upload multiple file using Angularjs and webapi.. This is my html table:

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

Here is my Angularjs Code for multiple file upload(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.");
    }
});

here is my function in webapi:

 public async Task<HttpResponseMessage> getDataForUploadFiles()
                {
                 }

but how to read the file deatils and access the file details from the controller method(getDataForUploadFiles)

6
  • are you getting files in $scope.files object ? Commented Jul 28, 2016 at 13:57
  • You specified the Route as getDataForUploadFiles and calling objXhr.open("POST", "/file_upload"); Which is clearly wrong. Commented Jul 28, 2016 at 13:58
  • You can leverage angularjs features to upload files for ease. stackoverflow.com/questions/24443246/… Commented Jul 28, 2016 at 14:00
  • no the route is correct..how to read data in webapi function???? Commented Jul 28, 2016 at 14:18
  • Whatever you are doing is correct. You need to check whether data object has data init and GetAllInbox has the same property types as data object. Then only mapping happens. Commented Jul 28, 2016 at 15:05

1 Answer 1

0

Try this

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

Controller Code

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!");
        });
    };
};

Handling the data server-side

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!");
}
Sign up to request clarification or add additional context in comments.

9 Comments

xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.setRequestHeader("X-File-Name", uf.name); is not working
Make sure that your API supports CORS and that Authorization is an allowed request header to be set. When you send an OPTIONS request to the endpoint your API should respond with the following response headers:
also try changing Content-Type to content-type although these are case-insensitive . It's worth giving it a try.
after writing the method like this public async Task<HttpResponseMessage> getDataForUploadFiles() { }
it is going to the controller with my code 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);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.