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)

Manoj Maharana
  • 145
  • 1
  • 1
  • 19

1 Answers1

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!");
}
Venkata Dorisala
  • 4,783
  • 7
  • 49
  • 90
  • xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.setRequestHeader("X-File-Name", uf.name); is not working – Manoj Maharana Jul 29 '16 at 07:50
  • 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: – Venkata Dorisala Jul 29 '16 at 07:56
  • also try changing `Content-Type` to `content-type` although these are `case-insensitive` . It's worth giving it a try. – Venkata Dorisala Jul 29 '16 at 07:57
  • after writing the method like this public async Task getDataForUploadFiles() { } – Manoj Maharana Jul 29 '16 at 08:05
  • 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); – Manoj Maharana Jul 29 '16 at 08:06
  • but i dont understand how to read the files and get the files – Manoj Maharana Jul 29 '16 at 08:09
  • you are doing manythings wrong here. 1. putting files in `data` object. Which is not required as webapi can take the multiple files directly. 2. You are not using traditional `angular upload` feature. Which is simple and 2 -3 lines of code. I have given the example in previous comments. – Venkata Dorisala Jul 29 '16 at 08:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118611/discussion-between-manoj-maharana-and-venky). – Manoj Maharana Jul 29 '16 at 08:31
  • where is the add button here?i have already add a button but it is not hitting the save method – Manoj Maharana Jul 29 '16 at 09:39