"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request.

However, the converted .xlsx file does not reach the client when I attempt to respond with it.

I simplified the code by passing a basic .xlsx file, but even that did not work.

JavaScript:

if (files[0].type == "application/vnd.ms-excel") {                
    console.log("XLS File");

    formData = new FormData();
    formData.append("xlsfile", files[0]);

    $.ajax({
        url: '/Home/ConvertToXlsx',
        type: 'POST',
        cache: false,
        processData: false,
        data: formData,
        contentType: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (response) {                        
            openXLSFile(response);            
        },
        error: function () {
            console.log("An Error occurred");
        }
    });
}

Controller:

public IActionResult ConvertToXlsx(IFormFile xlsfile) {

    //For simplification without conversion
    //var xlsconverter = new XLSConverter();
    //FileStreamResult response = xlsconverter.XLSConvert(xlsfile);

    var path = $"wwwroot/temp/";
    var filepath = Path.Combine(path, "test.xlsx");
    MemoryStream x = new MemoryStream();
    using(FileStream fs = System.IO.File.OpenRead(filepath)) {
        fs.CopyTo(x);
    }

    return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

}

The browser network tab shows Status: net::ERR_CONNECTION_RESET

Is there a setting that I am missing which is preventing me from responding with files?

Answer №1

To send a file to an action, consider employing the code snippet below:

if (files[0].type == "application/vnd.ms-excel") {                
    console.log("XLS-File");

    $.ajax({
        url: '/Home/ConvertToXlsx',
        type: 'POST',
        cache: false,
        processData: false,
        data: files[0],
        contentType: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (response) {                        
            openXLSFile(response);            
        },
        error: function () {
            console.log("An Error occurred");
        }
    });
}

If you wish to return a file with a specific content type, you may try using the following method:

public IActionResult ConvertToXlsx(IFormFile xlsfile)
        {
            return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }

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

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

Creating a custom route that is specific to a single ejs file

I'm trying to set up a URL like localhost:3000/hh234due with a unique ID that routes to a specific page. However, my current implementation is conflicting with other routes. How can I make the /:id route unique to one view? module.exports = fun ...

What is the best way to create an Excel spreadsheet by utilizing parameters from an AJAX search?

While implementing an AJAX search feature in my Rails application, I encountered a problem with generating Excel documents. Here is the relevant code snippet from the controller: def show @website = Website.find(params[:id]) if (current_user.id != @websit ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

Avoid Scrolling within an iFrame in HTML with the Use of #

I have a menu loading in an iframe with links using # like http://<location>/page.html#part1. When I click inside the iframe, the entire page outside of the iframe scrolls to the location of #. How can I stop this from happening? I only want the me ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

Trouble with browser autocomplete/saved form during ajax requests

Searching for information on browser autocomplete and form saving can be tricky, especially when trying to find solutions related to custom autocomplete with ajax. Many developers are interested in customizing autocomplete features for various reasons such ...

What is the best way to add a background image to a div using react?

My images folder contains 2 images. See the code snippet below from App.js: import "./styles.css"; import nf_logo from "./images/netflix_logo.png"; import nf_bg from "./images/netflix_bg.jpg;; const divStyle = { backgroundImag ...

Tips for moving text within a Canvas using a button to trigger the function that displays the text in a Javascript environment

Within my HTML, there is a canvas element with the id="myCanvas". When a button is clicked, it triggers this particular function: function writeCanvas(){ var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); va ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...

What in the world is going on with this code snippet? I'm completely stumped on how to fix this problem

Attempting to generate a custom element with unique properties function y(){ var g=document.createElement("div"); this.label="elephant"; return g; } y.prototype.customFunction=function(){ alert(arguments[0]+this.label); }; var b=new y(); b ...

Avoid closing the login modal/popup form if there is a validation error

Is there a way to prevent the popup login form from closing after submitting it if there is a validation error? I am working with node.js and ejs as my view engine. Login html form: <div class="modal"> <div class="modal__box" ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Facing difficulty transferring an array from React to Django

Trying to transfer an array from the React frontend (stored in local storage) to my view class in Django is resulting in the following error: Console Output: GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error) Django Logs: for qu ...

JQuery is blocking the submission of an HTML form

During my exploration of an AJAX/JQuery tutorial for a registration script that interacts with PHP/MySQL and is submitted via JQuery, I encountered a recurring issue. The problem lies in the form submitting directly to the action page instead of its intend ...

Changing the color of a marker on hover in Mapbox using leaflet.js

I have encountered an issue where setting the geojson triggers the mouseover event, causing an infinite loop and breaking functionality. I managed to fix it by changing it to click, but now I need to figure out how to make it work with hover. My goal is t ...