asp.net mvc文件下载名称编码

时间:2011-11-03 17:14:55

标签: c# asp.net-mvc encoding

我的应用程序允许用户下载文件,但文件名可以采用西里尔文编码。 当用户下载文件我希望名称像用户看到,但在控制器ContentDisposition不允许使用西里尔语编码的名称,我尝试将其转换为 UTF-8。 Chrome,IE和Opera下载文件的名称正确:

enter image description here firefox和safari有这样的东西


enter image description here

我的控制员:

 public ActionResult Download()
        {
            var name = Request.Params["Link"];
            var filename = Request.Params["Name"];


            filename = GetCleanedFileName(filename);

            var cd = new ContentDisposition
            {
                FileName = filename,
                Inline = false,
            };


            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(name, "application/file");
        }


        public static string GetCleanedFileName(string s)
        {
            char[] chars = s.ToCharArray();

            StringBuilder sb = new StringBuilder();

            for (int index = 0; index < chars.Length; index++)
            {
                string encodedString = EncodeChar(chars[index]);
                sb.Append(encodedString);
            }
            return sb.ToString();
        }

        private static string EncodeChar(char chr)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            StringBuilder sb = new StringBuilder();

            byte[] bytes = encoding.GetBytes(chr.ToString());

            for (int index = 0; index < bytes.Length; index++)
            {
                if (chr > 127)
                    sb.AppendFormat("%{0}", Convert.ToString(bytes[index], 16));
                else
                    sb.AppendFormat("{0}", chr);

            }

            return sb.ToString();
        } 

1 个答案:

答案 0 :(得分:1)

在这里,我们以此为例,返回通过控制器下载文件时我们希望的文件名。

http://www.simple-talk.com/dotnet/asp.net/asp.net-mvc-action-results-and-pdf-content/

FileResult有一个FileDownloadName属性,您可以设置该属性,用于设置用户下载时发送给Response的文件名。