How to download from memorystream?

Dondon510 261 Reputation points
2022-09-03T15:40:01.903+00:00

Hi,

My controller serves download xlsx file, like below:

        [HttpGet]  
        [Route("/Download/")]  
        public async Task<IActionResult> Download_Xlsx(string id)  
        {  
                    using (ExcelEngine excelEngine = new ExcelEngine())  
                    {  
  
                        ...  
                        ...  
  
                            using (MemoryStream ms = new MemoryStream())  
                            {  
                                workbook.SaveAs(ms);  
  
                                string fileName = Helper.Generate_NewGuid() + ".xlsx";  
                                string fileExt = fileName.Substring(fileName.IndexOf("."));  
  
                                return File(ms.ToArray(), new Helper().GetMimeTypes()[fileExt], Path.GetFileName(fileName));  
                                 
                            }  
                     }  
  
         internal Dictionary<string, string> GetMimeTypes()  
        {  
            return new Dictionary<string, string>  
            {  
                {".txt", "text/plain"},  
                {".pdf", "application/pdf"},  
                {".doc", "application/vnd.ms-word"},  
                {".docx", "application/vnd.ms-word"},  
                {".xls", "application/vnd.ms-excel"},  
                {".xlsx", "application/vnd.ms-excel"},  
                {".png", "image/png"},  
                {".jpg", "image/jpeg"}  
            };  
        }  

in ajax

      $.ajax({  
                            type: 'GET',  
                            url: '/Download',  
                            success: function (data)  
                            {  
                                alert(data); // it goes here! .. but I don't have an idea on how to download the file here.  
                                  
                            }  
                        });  

any help appreciated.. thanks a lot in advance

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. SurferOnWww 4,721 Reputation points
    2022-09-04T00:58:24.267+00:00

    You will have to write a script to get Blob form the received content and save the Blob in the disk.

    Shown below is a sample code which use XMLHttpRequest:

    function download() {  
      var url = "/Home/FileDownload";  
      var filename = "testfile";  
       
      var xhr = new XMLHttpRequest();  
      xhr.open('GET', url, true);  
      xhr.responseType = 'blob';  
      xhr.onreadystatechange = function (e) {  
        if (this.readyState == 4 && this.status == 200) {  
          var blob = this.response;  
       
          //IE and Edge can use msSaveBlob method   
          if (window.navigator.msSaveBlob) {  
            window.navigator.msSaveBlob(blob, filename + ".pdf");  
          } else {  
            var a = document.createElement("a");  
            // IE11 does not support URL API  
            var url = window.URL;  
            a.href = url.createObjectURL(new Blob([blob],  
                                         { type: blob.type }));  
            document.body.appendChild(a);  
            a.style = "display: none";  
            a.download = filename + ".pdf";  
            a.click();  
          }  
        }  
      };  
      xhr.send();  
    }  
    

    You will be able to use the jQuery 3 or above version. See the following article:

    Using jQuery's ajax method to retrieve images as a blob
    https://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.