B
B
Boris the Animal2020-06-03 00:58:12
JavaScript
Boris the Animal, 2020-06-03 00:58:12

JavaScript and downloading a file from an ASP.NET Core WebAPI server. Why does the file download as corrupted?

What could it be? I can't even imagine where to dig.

Error in Excel : content found in the book that could not be read I

use
js-file-download for downloading

On the server I distribute it like this:

using System.IO;
using System.Threading.Tasks;
using ClosedXML.Excel;
using Microsoft.AspNetCore.Mvc;

namespace Something.Extensions
{
    public static class XLWorkbookExtensions
    {
        public static Task<FileStreamResult> DeliverAsync(this XLWorkbook workbook, 
            string fileName = "attachment",
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            return Task.Run(() =>
            {
                var memoryStream = new MemoryStream();
                workbook.SaveAs(memoryStream);
                memoryStream.Seek(0L, SeekOrigin.Begin);
                var fileStream = new FileStreamResult(memoryStream, contentType);
                fileStream.FileDownloadName = fileName;
                return fileStream;
            });
        }
    }
}


//
        [HttpPost]
        [Route("get-report")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> GetReport([FromBody] ReportParams parameters)
        {
            _logger.Debug(GET_REPORT_MESSAGE_TEMPLATE);
            if (parameters.From >= parameters.To)
            {
                return BadRequest(ErrorObject("Incorrect combination of parameters."));
            }

            try
            {
                // Какой-то код...
                XLWorkbook workbook = await _reportBuilder.Build(data);
                return await workbook.DeliverAsync($"Report_{DateTimeOffset.UtcNow:yyyy-dd-M--HH-mm-ss}.xlsx");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, GET_REPORT_MESSAGE_TEMPLATE);
                return InternalServerError();
            }
        }


If I download using the Postman application , then the file is normally downloaded and opened in Excel . But when downloading it in JavaScript , it is downloaded damaged.

Log from Postman
Request Headers
POST /api/get-report HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Cache-Control: no-cache
Postman-Token: dc3e6175-0fcd-4613-9ef1-fcbd777dfb5b
Host: localhost:5001
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 82
Cookie: AppCookie=CfDJ8I5lw_HuaDpjA7DmwwY


Request Body
{
    "from": "2020-01-10T23:59:59+00:00",
    "to": "2021-01-01T23:59:59+00:00"
}


response headers
HTTP/1.1 200 OK
Date: Tue, 02 Jun 2020 20:40:34 GMT
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Server: Kestrel
Content-Length: 66060
X-Content-Type-Options: nosniff
X-Xss-Protection: 1
X-Frame-Options: DENY
Content-Disposition: attachment; filename=Report_2020-02-6--20-40-29.xlsx; filename*=UTF-8''Report_2020-02-6--20-40-29.xlsx

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris the Animal, 2020-06-04
@Casper-SC

The problem was that the parameter responseType: 'blob', was not passed to axios .

getReport(dateFrom, dateTo) {
        return axios.post(this.config.getReportUrl, {
            from: dateFrom,
            to: dateTo
        }, {
            baseURL: this.config.baseUrl,
            withCredentials: true,
            responseType: 'blob',
            headers: {
                "Accept": "*/*",
                "Cache-Control": "no-cache",
            }
        });
    };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question