"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

Searching in jquery not functioning as intended

Greetings! I'm in the process of creating a live search feature similar to what's demonstrated at this link. However, I've encountered a minor issue with this snippet of code: jQuery("#result").on("click",function(e){ var $clicked = $(e.ta ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Discover the process of extracting HTML content that's stored within a JavaScript variable

Having a HTML snippet stored in a variable, like this: var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World' I am looking to extract the value of the "t ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

Generating random indexes for the Answer button to render

How can we ensure that the correct button within the Question component is not always rendered first among the mapped incorrect buttons for each question? Is there a way to randomize the positions of both correct and incorrect answers when displaying them, ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

Enhancing the visual display of a webpage using AngularJS

Hello there! I'm currently working on enhancing an angular 1.6 app and have encountered a dilemma that needs solving. Let me provide some context: The page in question is a lengthy form consisting of thirty questions. The client-side logic includes nu ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

After making an AJAX call, the table data can be found in page 1 under the tbody

Can anyone help me with this issue? I've gone through all the guides related to this problem and followed them step by step, but still no success. After populating the table using an AJAX call, all the data appears on a single page only. I attempted ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Tips for eliminating objects with a sessionID:null value from the nested array within an array of objects using JavaScript

[ { "_id": "5ecda7f5310bee6f4b845add", "firstname": "john", "lastname": "smith", "sessions": [ { "_ ...

Can anyone share a straightforward yet practical demonstration of using jquery.JsPlumb?

In my quest for a reliable graph-visualization JavaScript library, I recently came across jsPlumb at http://jsplumb.org. The examples I've seen truly showcase its advanced capabilities and attractive design. However, despite the extensive documentatio ...

A guide to retrieve data attributes in Vue.js

When my button is clicked, a modal pops up with data passed through data attributes. The button code looks like this: <button class="edit-modal btn btn-info" data-toggle="modal" data-target="#editModal" :data-id=item.id ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

The Angular JS Root scope is modified after submitting a form

I'm new to Angular JS and I'm trying to figure out how to save an object into $rootScope in my application. However, when I try to make a post request without including the object from rootScope, it doesn't work as expected. Now, on a newly ...