Anzolin
Anzolin

Reputation: 43

Chrome modifying long file names when download them (using c# FileContentResult)

In a list of generated reports, have a link to download them. The contents of these reports are stored in the database. When I perform the download a report, use the code below:

return new FileContentResult (report.FileContents, mimeType)
{
    FileDownloadName = report.Title + report.Extension
};

In many cases, the filename exceeds 50 characters and when I do download the report using Google Chrome, the browser ignores the filename generated in the header and tries to save the file with the last parameter of the download link, which case the ID of report, example: the download link is http://appname.com/report/download/123 and return the browser is "123.pdf" but should be "Relatório de probabilidade e risco de processos.pdf". But when I use Mozilla Firefox or IE, the problem does not occur.

Has anyone experienced this situation?

Upvotes: 2

Views: 1495

Answers (1)

Anzolin
Anzolin

Reputation: 43

The problem is not related to the number of characters, but referring to special characters. I created a function that removes special characters and tried the filename.

Function:

/// <summary>
/// Remove characters from string
/// </summary>
public static string RemoveSpecialCharacters(string text, bool allowSpace)
{
    var normalizedString = text;

    // Prepare the symbol table.
    var symbolTable = new Dictionary<char, char[]>();

    symbolTable.Add('a', new char[] { 'à', 'á', 'ä', 'â', 'ã' });
    symbolTable.Add('c', new char[] { 'ç' });
    symbolTable.Add('e', new char[] { 'è', 'é', 'ë', 'ê' });
    symbolTable.Add('i', new char[] { 'ì', 'í', 'ï', 'î' });
    symbolTable.Add('o', new char[] { 'ò', 'ó', 'ö', 'ô', 'õ' });
    symbolTable.Add('u', new char[] { 'ù', 'ú', 'ü', 'û' });

    // Replaces the symbols.
    foreach (var key in symbolTable.Keys)
    {
        foreach (var symbol in symbolTable[key])
        {
            normalizedString = normalizedString.Replace(symbol, key);
        }
    }

    // Remove the other special characters.
    if (allowSpace)
        normalizedString = System.Text.RegularExpressions.Regex.Replace(normalizedString, @"[^0-9a-zA-Z.-_\s]+?", string.Empty);
    else
        normalizedString = System.Text.RegularExpressions.Regex.Replace(normalizedString, @"[^0-9a-zA-Z.-_]+?", string.Empty);

    return normalizedString;
}

Corrected code:

...

string reportName = StringUtils.RemoveSpecialCharacters(report.Title, true);

return new FileContentResult(report.FileContents, mimeType)
{
    FileDownloadName = reportName + report.Extension
};

Thank you for your attention.

Upvotes: 1

Related Questions