Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileContentResult and international characters

Tags:

asp.net-mvc

I am using a fileContentResult to render a file to the browser. It works well except that it throws an exception when the fileName contains international characters. I remember reading somewhere that this feature does not support international characters but I am sure there mustbe a workaround or a best practice people follow in cases the application needs to upload files in countries other than US.

Does anyone know of such a practice?Here is the ActionResult Method

public ActionResult GetFile(byte[] value, string fileName)
    {
        string fileExtension = Path.GetExtension(fileName);
        string contentType = GetContentType(fileExtension); //gets the content Type
        return File(value, contentType, fileName);
    }  

THanks in advance

Susan

like image 520
suzi167 Avatar asked Jul 16 '09 18:07

suzi167


2 Answers

public class UnicodeFileContentResult : ActionResult {

    public UnicodeFileContentResult(byte[] fileContents, string contentType) {
        if (fileContents == null || string.IsNullOrEmpty(contentType)) {
            throw new ArgumentNullException();
        }

        FileContents = fileContents;
        ContentType = contentType;
    }

    public override void ExecuteResult(ControllerContext context) {
        var encoding = UnicodeEncoding.UTF8;
        var request = context.HttpContext.Request;
        var response = context.HttpContext.Response;

        response.Clear();
        response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", (request.Browser.Browser == "IE") ? HttpUtility.UrlEncode(FileDownloadName, encoding) : FileDownloadName));
        response.ContentType = ContentType;
        response.Charset = encoding.WebName;
        response.HeaderEncoding = encoding;
        response.ContentEncoding = encoding;
        response.BinaryWrite(FileContents);
        response.End();
    }

    public byte[] FileContents { get; private set; }

    public string ContentType { get; private set; }

    public string FileDownloadName { get; set; }
}
like image 88
AlexMAS Avatar answered Oct 06 '22 06:10

AlexMAS


I don't think it's possible to download files with international characters in the file name. The file name is part of the Content-disposition header, and like all HTTP headers, there's no way of using a different encoding other than ASCII that will work across all browsers and proxies.

Uploading files with international characters should be no problem, though, since the file name is transmitted as normal form data (application/www-url-encoded)

like image 25
chris166 Avatar answered Oct 06 '22 08:10

chris166