加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – FileContentResult和国际字符

发布时间:2020-12-16 07:07:45 所属栏目:asp.Net 来源:网络整理
导读:我正在使用fileContentResult将文件呈现给浏览器.除了在fileName包含国际字符时抛出异常,它才能正常工作. 我记得在某个地方读过这个功能不支持国际字符,但我确信在应用程序需要在美国以外的国家上传文件的情况下,必须有一个解决方法或最佳实践. 有谁知道这样
我正在使用fileContentResult将文件呈现给浏览器.除了在fileName包含国际字符时抛出异常,它才能正常工作.
我记得在某个地方读过这个功能不支持国际字符,但我确信在应用程序需要在美国以外的国家上传文件的情况下,必须有一个解决方法或最佳实践.

有谁知道这样的做法?这是ActionResult方法

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

提前致谢

苏珊

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读