-1

I'm generating an Excel file and saving it to server disk, now I need to safely deliver this file to the user. The code below achieve a status code 200 at the browser, but no file is available to download.

How should I do it?

public ActionResult GenerateReport(int customer_id)
{
    \\file being created

    string fileName = "newReport.xlsx";
    string filePath = ConfigurationManager.AppSettings["serverSetting"].ToString() + "\\Content\\reports\\temp\\" + fileName;
    excel.SaveAs(new FileInfo(filePath));
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    return File(filePath, contentType, fileName);
}

On the frontend:

$('#btnGenerateReport').on('click', function () {

    $.ajax({
        url: '/GeneralReport/GenerateReport',
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
            customer_id: customer_id
        }),
        success: function () {
            $.Notification.autoHideNotify('success', 'top right', 'Success', 'Success');
        },
        error: function () {
            $.Notification.autoHideNotify('error', 'top right', 'Error', 'Error');
        }
    });
});
rd1218
  • 134
  • 12
  • On the browser side, are you making an ajax request, or navigating via a link? – Andrew Williamson Nov 06 '22 at 22:19
  • An ajax request. I've updated the question – rd1218 Nov 06 '22 at 22:21
  • I would say you need to change the question. Your server code looks fine. The problem is on the client - you've got the file in-memory in the browser, you need to save it to disk. See [this question](https://stackoverflow.com/q/4545311/2363967) for an example – Andrew Williamson Nov 06 '22 at 22:27

1 Answers1

0

So, my case was a frontend issue: I need to correctly get the information available and process it. The backend shown at the question is correct.

The mais issue was to include xhrFields: { responseType: 'arraybuffer' }, at the AJAX.

$('#btnGenerateReport').on('click', function () {    
    $.ajax({
        url: '/GeneralReport/GenerateReport',
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
            customer_id: customer_id
        }),
        xhrFields: {
            responseType: 'arraybuffer'
        },
        success: function (response, status, xhr) {
            var filename = getFileName(xhr);
            var blob = new Blob([response]);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            link.click();
            $.Notification.autoHideNotify('success', 'top right', 'Success', 'Success');
        },
        error: function () {
            $.Notification.autoHideNotify('error', 'top right', 'Error', 'Error');
        }
    });
});

function getFileName(xhr) {
    var filename = '';
    var disposition = xhr.getResponseHeader('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        var matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
        }
    }
    return filename;
}
rd1218
  • 134
  • 12