Home > Mobile >  ActionResult - return file to the user/browser
ActionResult - return file to the user/browser

Time:11-09

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

CodePudding user response:

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;
}
  • Related