0

I have to download large archive files on client browser. To achieve it I called controller method which returned Stream:

Server code:

[HttpPost]
public ActionResult Download(params Guid[] UIds)
{
      if (CampaignId == null)
          throw new ApplicationException(Constants.SESSION_ERROR);
    
      using (ZipFile zip = new ZipFile(Encoding.GetEncoding("cp866")))
      {
           zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
    
           foreach (PPService.FileResult file in GetDocs(CampaignId.Value, UIds))
                        zip.AddEntry(
                            file.FileName,
                            file.Content);
    
            using (MemoryStream memoryStream = new MemoryStream())
            {
                 zip.Save(memoryStream);
                 return File(memoryStream.ToArray(), "application/zip");
            }
       }
}

Client code:

var url = '@Url.Action("Download", "Home")';
    var archAction = url;
    var form = document.createElement("form");
    form.setAttribute("id", "downloadPublicDocs");
    form.setAttribute("method", "post");
    form.setAttribute("action", archAction);
    form.setAttribute("style", "display: none;");
    form.target = "_self";        
    document.body.appendChild(form);
    
    form.submit();
    
    $("#archLoader").fadeIn(1000);

Then I need to catch submit request to show user "Download completed" and do this $("#archLoader").fadeOut(1000);

I had tried to use:

  1. form.addEventListener("onload", async (event) => {}); not working. onload event not fired at all.

  2. $.post(form.requestSubmit()) .done(function (e) { handler here }) .always(function () {}) .fail(function () {});

    not working

  3. var xhr = new XMLHttpRequest(); xhr.open("POST", form.requestSubmit()); xhr.onload = function (event) { alert("!!!"); // raw response };

    not working. onload event not fired

    xhr.onreadystatechange = function (e) {}

    not working. onload event not fired

Is there any solution? I couldn't use any way except form approach, because I will get an error. But how could I handle response?

Thanks.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Natalia
  • 313
  • 2
  • 8
  • 1
    you can't ... form submit loads a new page - as for your attempts number 2 and 3 - `requestSubmit` does not do what you think - and it returns `undefined` - so ... that's enver going to do what you think – Jaromanda X Aug 15 '22 at 06:23
  • check this way : https://stackoverflow.com/a/51730069/1910035 – r043v Aug 15 '22 at 07:12

0 Answers0