Search code examples
javascriptasp.net-coremodel-view-controllerxmlhttprequest

Running process after getting files in controller using Request.Form.Files


I've got a problem in my ASP.net Core application. I use MVC. I send a file from js to controller using:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/Test/Sing", true);
xhr.send(fd);

then I got it in controller action:

[HttpPost]
    public IActionResult Sing()
    {
        var file = Request.Form.Files[0];
        byte[] filedata = null;
        using (var target = new MemoryStream())
        {
            file.CopyTo(target);
            filedata = target.ToArray();
        }

          \\some filedata processing

        return RedirectToAction("Question");
    }

The filedata is something that I need to process and then redirect to another action. When I put a breakpoint at the end of using (MemoryStream) I can see that the filedata is filled with data I need but when I want to redirect to action nothing happens. It looks like a process with the xmlhttprequest is still running on the client side and waiting for response. Am I right? How to get the file, cut the process, perform some file processing and be able to redirect to another action?


Solution

  • You should manually handle the redirect using window.location.href in success callback function of ajax/XMLHttpRequest .

    If using XMLHttpRequest ,you can add listener for load events ,the listener must be added before the send() function:

    function reqListener () {
        window.location.href = "url";
    }
    
    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", "http://www.example.org/example.txt");
    oReq.send();
    

    If using AJAX redirect in success callback function :

    success: function (response) {
        window.location.href = "url";
    }
    

    Controller :

     return Json("ok");
     //Or return the url 
     return Json(new { redirectToUrl = Url.Action("action", "contoller") });