Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

319
Visualizações
.net Core send xlsx file as response for Ajax request

My web-application can only work with .xlsx-files. I created a function in my controller, which converts a .xls-file into an .xlsx-file. The conversion works totally fine. So whenever I try to open a .xls-file, I send it via Ajax request.

After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.

Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.

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");

}

In the browser-network tab I get Status: net::ERR_CONNECTION_RESET screenshot here

Am I missing a setting somewhere, which causes I simply can't respond with files?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

If you want to pass file to action,try to use the following code:

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");
        }
    });
}

And if you want to return file with content type,you can try to use:

public IActionResult ConvertToXlsx(IFormFile xlsfile)
        {
            return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda