简体   繁体   English

如何使用XMLHttpRequest和ASP.net MVC发布图像

[英]How to Post images using XMLHttpRequest and ASP.net MVC

I am trying to upload multiple image with AngularJS. 我正在尝试使用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. 由于必须跟踪每个文件的进度,因此我决定使用XMLHttpRequest将图像发布到ASP.net MVC控制器。 the js code is as follows js代码如下

$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 我尝试了以下ASP.net MCV控制器来接收文件

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. 问题是我发现httpRequest.Files.Count始终为零。 Why? 为什么? i googling many time but do not understand what is going wrong. 我谷歌搜索了很多时间,但不知道出了什么问题。 any one there to help me 那里有人帮我

I had problems with Request.Files but it helped me to take an approach, it might be useful for you as well 我在使用Request.Files时遇到问题,但它帮助我采取了一种方法,这可能对您也很有用

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: 并将您的XHR对象移动到循环中:

  $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.")
      }

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用XMLHttpRequest和asp.net MVC将较大的Blob发布到服务器? - How post a large blob to server using XMLHttpRequest and asp.net MVC? 在ASP.NET MVC中使用JavaScript XMLHttpRequest() - using JavaScript XMLHttpRequest() with ASP.NET MVC 如何使用XmlHttpRequest和ASP.NET MVC处理文件上传错误? - How to deal file upload error with XmlHttpRequest and asp.net mvc? 如何使用 asp.net 中的 XMLHttpRequest 从带有 Post 方法的页面获取响应文本? - How to get responsetext from a Page with Post method using XMLHttpRequest in asp.net? ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法 - ASP.NET Core 2.1 MVC send data from JavaScript to Action method using XMLHttpRequest 使用javascript访问Asp.net mvc4中的图像 - accessing the images in Asp.net mvc4 using javascript 是否可以使用 XMLHttpRequest/FormData 将 HTTP POST 发布到标准 ASP.Net Web 表单? - Is it possible to make a HTTP POST to a standard ASP.Net Web Form using XMLHttpRequest/FormData? 在ASP.NET MVC应用程序中使用AngularJS发布表单 - Post an form using AngularJS in an ASP.NET MVC application 使用@ Html.ActionLink发布textarea-ASP.NET MVC 5 - Post textarea using @Html.ActionLink - ASP.NET MVC 5 XMLHttpRequest.open带有参数asp.net的POST请求 - XMLHttpRequest.open POST request with parameters asp.net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM