0

I am trying to upload multiple image with AngularJS. As i have to track the progress of each file i decide to use XMLHttpRequest to Post the image to ASP.net MVC controller. the js code is as follows

$scope.UploadImage=function()
    {
        var reqObj = new XMLHttpRequest();



        //event Handler
        reqObj.upload.addEventListener("progress", uploadProgress, false)
        reqObj.addEventListener("load", uploadComplete, false)
        reqObj.addEventListener("error", uploadFailed, false)
        reqObj.addEventListener("abort", uploadCanceled, false)



        for (var i = 0; i < $scope.fileList.length; i++)
        { 
             var fileToUpload = $scope.fileList[i].file;

             var fd = new FormData();

            fd.append('file', fileToUpload);

            reqObj.open("POST", "/WebDevelopment/SaveImage", false);
            reqObj.setRequestHeader("Content-Type", "multipart/form-data");


            reqObj.send(fd);
        }

        function uploadProgress(evt) {

            $scope.uploadProgressCount = Math.round(evt.loaded * 100 / evt.total);
            $scope.$apply();
        }


        function uploadComplete(evt) {
            /* This event is raised when the server send back a response */
            alert(evt.target.responseText)
        }

        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.")
        }

        function uploadCanceled(evt) {

            alert("The upload has been canceled by the user or the browser dropped the connection.")
        }

    }

I tried the following ASP.net MCV Controller to receive the file

public JsonResult SaveImage()
        {

            string path = "";
            var httpRequest = System.Web.HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
               // do something
            }
}

the problem is i found httpRequest.Files.Count is zero all time. Why? i googling many time but do not understand what is going wrong. any one there to help me

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
himadri
  • 626
  • 5
  • 19

1 Answers1

0

I had problems with Request.Files but it helped me to take an approach, it might be useful for you as well

public class WebDevelopmentController : Controller
{
    [HttpPost]
    public JsonResult SaveImage()
    {
        var fileContents = new byte[Request.ContentLength];
        Request.InputStream.Read(fileContents, 0, Request.ContentLength);
        var filename = Request.Headers["X-File-Name"];
        var fileType = Request.Headers["X-File-Type"];

        var file = new UploadedFile() {
            Filename = filename,
            ContentType = fileType,
            FileSize = fileContents != null ? fileContents.Length : 0,
            Contents = fileContents
        };

        // save the file.

        var saveToFileLoc = string.Format("{0}\\{1}",
                                    Server.MapPath("/Content"),
                                    file.Filename);

        var fileStream = new FileStream(saveToFileLoc, FileMode.Create, FileAccess.ReadWrite);
        fileStream.Write(file.Contents, 0, file.FileSize);
        fileStream.Close();

        return null;
    }

    public class UploadedFile
    {
        public int FileSize { get; set; }
        public string Filename { get; set; }
        public string ContentType { get; set; }
        public byte[] Contents { get; set; }
    }
}

And move your XHR object to the loop:

  $scope.UploadImage = function() {

      for (var i = 0; i < $scope.fileList.length; i++) {

          var reqObj = new XMLHttpRequest();

          //event Handler
          reqObj.upload.addEventListener("progress", uploadProgress, false)
          reqObj.addEventListener("load", uploadComplete, false)
          reqObj.addEventListener("error", uploadFailed, false)
          reqObj.addEventListener("abort", uploadCanceled, false)

          var fileToUpload = $scope.fileList[i].file;

          var fd = new FormData();

          fd.append('file', fileToUpload);

          reqObj.open("POST", "/WebDevelopment/SaveImage", false);
          reqObj.setRequestHeader("Content-Type", "multipart/form-data");


          reqObj.send(fd);
      }

      function uploadProgress(evt) {

          $scope.uploadProgressCount = Math.round(evt.loaded * 100 / evt.total);
          $scope.$apply();
      }


      function uploadComplete(evt) {
          /* This event is raised when the server send back a response */
          alert(evt.target.responseText)
      }

      function uploadFailed(evt) {
          alert("There was an error attempting to upload the file.")
      }

      function uploadCanceled(evt) {

          alert("The upload has been canceled by the user or the browser dropped the connection.")
      }

  }
Bartosz Czerwonka
  • 1,631
  • 1
  • 10
  • 11
  • thanks for replay. i tried your solution but Request.InputStream.Read(fileContents, 0, Request.ContentLength); gives error.(Maximum Length exced) – himadri Oct 18 '15 at 02:54
  • How big is this file? – Bartosz Czerwonka Oct 18 '15 at 05:43
  • Change max uploaded size file like this : http://stackoverflow.com/a/3853785/4599089 – Bartosz Czerwonka Oct 18 '15 at 05:55
  • Thanks it works...But the Image save at directory is blank. i mean when i upload 16kb image then a file o 16kb has saved. but when i want to preview, image does not shown – himadri Oct 18 '15 at 08:52
  • I tried this code and it's working - here is client side - http://plnkr.co/edit/6SzdYVbmGEhc7drO6U93?p=preview (change url in this code) . I used this https://github.com/ghostbar/angular-file-model for input file in angular – Bartosz Czerwonka Oct 18 '15 at 09:00
  • Did `uploadProgress` will work if You send *synchronous* request?? – nelek Nov 08 '15 at 12:16