Accessing Excel files through Ajax and MemoryStream successfully downloads new Excel files; however, this method may not work for existing Excel files already stored

Currently, I am working on a .Net 6 Razor pages application where I have successfully implemented the functionality to download an Excel file on a button click via Ajax. The approach involves creating a new Excel workbook in memory stream using OpenXML.

C# Code

    public IActionResult OnPostAjaxExport(string somedata)
    {
        // Creating a dummy data table
        DataSet ds = MakeDummyDataSet();

        // Exporting Excel via Memory Stream
        MemoryStream ms = ExportDataSetViaMemoryStream(ds);
        return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }

    private MemoryStream ExportDataSetViaMemoryStream(DataSet ds)
    {
        MemoryStream memoryStream = new MemoryStream();

        using (var workbook = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
        {
            var workbookPart = workbook.AddWorkbookPart();
            workbook.WorkbookPart.Workbook = new Workbook();
            
            // Additional code to populate the workbook...

            memoryStream.Seek(0, SeekOrigin.Begin);
            return memoryStream;
        }
   }
       

Ajax code

    $.ajax({
        type: "POST",
        url: "/Index?handler=AjaxExport",                                   
        data: payload,           
        xhrFields: {
            responseType: 'blob'
        },
        headers: {
            RequestVerificationToken:
                $('input:hidden[name="__RequestVerificationToken"]').val()
        },
        success: function (result) {               
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(result);
            a.href = url;
            a.download = 'download.xlsx';
            a.click();
            window.URL.revokeObjectURL(url);
        },
        error: function (result) {
            alert("error: " + JSON.stringify(result));
        }
     });

Everything is functioning as expected with this setup. However, a new requirement has surfaced which involves downloading pre-existing Excel files saved in a physical location on the server.

The challenge here is that the path to these files is not directly accessible in the browser. To tackle this, I attempted to read the files into memory stream and return them to the Ajax function following the same method used earlier.

Here is what I tried:

    public IActionResult OnPostDownloadPreGeneratedFile()
    {            
         string FilePath = @"C:\Manas\FilePath\DownloadTest\payload2.xlsx";
         string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";           

        // Read the file and prepare memory stream

        MemoryStream ms = new MemoryStream();
        FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        ms.Seek(0, SeekOrigin.Begin);
        file.CopyTo(ms);

        return new FileStreamResult(ms, ContentType);           
        
    } 

Unfortunately, this approach does not seem to work, despite creating the same type of memory stream as before.

No errors are displayed in the console or Ajax call. After the C# code returns the FilestreamResult, nothing happens in the browser.

I am seeking advice on how to resolve this issue and make it functional. Any suggestions would be greatly appreciated.

Answer №1

After much searching, I finally discovered the answer. All I needed to do was implement the following code snippet:

 public IActionResult OnPostDownloadPreGeneratedFile()
 {            
     string FilePath = @"C:\MyFolder\Files\DownloadMe\payload2.xlsx";
     string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";           

    //open and read the file, then create a memory stream

     var stream = new FileStream(FilePath, FileMode.Open);
     return new FileStreamResult(stream, ContentType);         
    
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fullcalendar not displaying any events

As a beginner programmer, I'm struggling to make this code work (sourced from here). It's using MySQL to store data, and while I want to grasp all its components, my understanding of ajax and jQuery is still in its early stages. The code depends ...

Ajax form: validating and handling errors

I am currently working on an Ajax form with validation that is functioning correctly. However, I am facing an issue with my POST Action: [HttpPost] public ActionResult AddUpdateConfigs(StorageConfigurationModel modelbind) { if (ModelState.IsValid) ...

What is the best way to maintain data types of variables within an object sent via ajax?

I'm sending an object via ajax to a PHP script for processing. Here's how I'm doing it: var Obj = {id:1, name:"John", value:12.1}; $.ajax({ url : "myfile.php", type : 'POST', data : Obj, success : ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

Having trouble getting Selenium RC's fireEvent() method to function properly in a C# environment

Currently working on an automated test for a sign-up page where each textbox is validated upon blur. The Sign up button will only be enabled if all textboxes pass validation. For each textbox, I've implemented the following actions: selenium.Type(te ...

An issue has arisen where FormData fails to send the value of a

My current issue involves submitting a form using FormData. Interestingly, all input types are functioning as expected except for checkboxes. When the checkbox value is set to 1 or 0, Ajax fails to post it. <form id="update-form" method="PUT" enctype= ...

Using JavaScript, is there a way to modify a JSON parameter within an API?

My API provides JSON data structured like this: [{"NAME":"john","SURNAME":"johny","ADULT":"3","CHILD":"3","BABY":"0",}] In my JavaScript function, I need to send a request to a web service that will update the value of "BABY" from "0" to "1". Can this be ...

The selection feature is not supported for the type of input element in jQuery

I'm currently attempting to utilize AJAX to send a form with jQuery. However, upon clicking the submit button (which is technically a link), I encountered an error. The error displayed in the console is as follows: Failed to read the 'selection ...

Is there a way to transfer a JavaScript variable created by an API to a PHP variable within a form submission?

I have some variables that are being generated by a JavaScript script and I am looking for the most effective way to pass them back to the PHP program that initiated the script. Since there are several variables (4-5), I prefer not to pass them through the ...

Fetch content from an external website and display it on my own website using AJAX

Can I embed an external website within my own webpage? Is there a security concern with doing this, or is it simply too difficult to achieve? If embedding is possible, would utilizing an ajax call be necessary? Appreciate any guidance on this matter. ...

"Successfully made an Ajax request to the web handler, however, the response did not

Within my ASP.NET project, I have a Generic handler with the following code: public void ProcessRequest ( HttpContext ctx ) { try { ctx.Response.ContentType = "text/json"; var jsonData = new StreamReader(ctx.Request.InputStrea ...

Generate visual content from written text with the use of a form and store it on the

Struggling to implement a php function on my webpage that generates an image from text input. However, nothing appears to be happening when I execute the code: PHP - $to = $paths. '/card.png'; if (isset($_POST['make_pic'])) { $text = ...

Sending data from Flask to Ajax

Upon accessing the main page, my Flask application generates a base Jinja template with specific elements: <div><span id="var_1">{{ var1|safe }}</span></div> <div><span id="var_2">{{ var2|safe }}</span></div> ...

Why is it that the value of "json_encode( $custom_query['query_vars']" is null?

After attempting to pass variables from a PHP function using wp_localize_script into a jQuery script, I encountered an issue with a NULL variable that I can't seem to figure out. I'm hopeful that someone else might be able to identify the proble ...

The URL in a request is altered prior to execution

I am encountering an issue with my NodeJS application where it automatically appends my domain to the URL set in my http request. How can I prevent this from happening? I have tried to search for similar problems but have not found any relevant solutions. ...

Utilizing Spiderable within Meteor results in the replication of head content before it is presented in the body tags

Having trouble with my meteor site, thought it was Google indexing, now suspecting an issue with the Spiderable package. Meteor version 1.1.0.3 is in use, along with spiderable package and gadicohen:phantomjs as suggested by meteorpedia. The current issu ...

Unexpected behavior with [FromBody] in ASP.NET Core

I am encountering an issue with my ASP.NET Core web app. It works fine when using the following controller implementation: [HttpPost] public ActionResult SetAssignment() { string b = ""; using (StreamReader rdr = new StreamReader(Request ...

Saving data to a file through ajax

Still getting the hang of using AJAX, so I'm diving in to learn more. Starting with an html page: <html> <script type="text/javascript" src="jquery-1.12.3.min.js"></script> <script> function write(){ $.ajax({ ...

The old DLL is causing a reference error when called upon

While working with a TwitchLib reference and utilizing Newtonsoft.Json 7.0.0, I encountered an error every time I visited the page that calls Twitch lab. The error message displayed is: "Could not load file or assembly 'Newtonsoft.Json, Version=7.0.0 ...

"Utilize Ajax and PHP to seamlessly upload a PDF file directly into a MYSQL database

I am trying to figure out how to upload a pdf file from user input into my MySQL database. I have provided code that displays a user registration form with the option to upload a PDF file. My goal is to use AJAX to post this data to a PHP script for storag ...