Why do spaces in the file name force IE to remove the file extension when the file is downloaded?

I am using EPPlus to create an Excel file from CSV that works without problems. Unfortunately, the code below forces Internet Explorer 9, 10, and 11 to refuse the file extension .xlsx, while Chrome and Firefox do not. If I remove spaces from the file name, the file extension works as expected in IE.

public FileStreamResult DetailsExcel(string id)
{
    string custName;
    var csv = this.GetCsvForCustomer(id, out custName);
    var fileName = String.Format("Report for {0} ({1:d-M-yyyy HH mm})",
        custName, DateTime.Now);

    MemoryStream stream;

    using (var excelPackage = new ExcelPackage())
    {
        var ws = excelPackage.Workbook.Worksheets.Add(fileName);
        ws.Cells["A1"].LoadFromText(csv, this._excelTextFormat);
        stream = new MemoryStream(excelPackage.GetAsByteArray());
    }

    return File(stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        fileName + ".xlsx");
}

The two software mechanisms that I have found that work somewhat, are to wrap the file name in quotation marks or in an UrlEncode string. Everyone has problems:

String.Format("\"{0}\".xlsx", fileName)
// above renders: __Report for Customer (20-2-2014 11 04)__.xlsx

HttpUtility.UrlEncode(fileName + ".xlsx")
// above renders: Report+for+Customer+(20-2-2014+11+04).xlsx

None of the above options are optimal. How to include spaces in the file name without losing the file extension when the user browses IE?

+4
1

, . , MemoryStream, File.

, MemoryStream . , :

public ActionResult DetailsExcel(string id)
{
    byte[] stream;  // changed to byte array

    using (var excelPackage = new ExcelPackage())
    {
        var ws = excelPackage.Workbook.Worksheets.Add(fileName);
        ws.Cells["A1"].LoadFromText(csv, this._excelTextFormat);
        stream = excelPackage.GetAsByteArray();  // removed MemoryStream
    }

    return File(stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        fileName + ".xlsx");
}
0

Source: https://habr.com/ru/post/1527970/


All Articles