具有特定文件名和 Safari 或 Chrome 的 ASP.NET MVC FileResult

发布于 2024-10-01 21:07:53 字数 602 浏览 4 评论 0原文

我在 FileResult 返回具有特定文件名的文件时遇到问题。在数据库中,文件名只是 ID + 扩展名(例如:456789.mp3)

这段代码

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/octet-stream", "myfile.mp3");

适用于除 Webkit 浏览器(Chrome、Safari)之外的所有浏览器。 Chrome 和 Safari 以原始文件名 (456789.mp3) 接收文件。当我使用 Safari 添加标头时,

Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.mp3");

会收到文件为 myfile.mp3attach(请注意“attach”附加到扩展名?),但是 Chrome 会收到此文件为 myfile.mp3,attach(它将“,attach”附加到扩展名)

有没有人经历过有这样的问题吗?

谢谢

I'm having problems with FileResult returning a file with a specific filename. In the database the filename is just and ID + extension (e.g: 456789.mp3)

This piece of code

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/octet-stream", "myfile.mp3");

Work well in every browser except Webkit browsers (Chrome, Safari). Chrome and Safari receive files as original filename (456789.mp3). When I add headers with

Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.mp3");

Safari receives the file as myfile.mp3attach (notice "attach" appended to the extension?), however Chrome receives this file as myfile.mp3,attach (it appends ",attach" to the extension)

Has anyone experienced this kind of a problem?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ˇ宁静的妩媚 2024-10-08 21:07:53

它帮助了我:

        var encoding = System.Text.Encoding.UTF8;
        Response.Charset = encoding.WebName;
        Response.HeaderEncoding = encoding;

            Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", (Request.Browser.Browser == "IE") ? HttpUtility.UrlEncode(fileName, encoding) : fileName));

        return File(fs, contentType, fileName);

It has helped me:

        var encoding = System.Text.Encoding.UTF8;
        Response.Charset = encoding.WebName;
        Response.HeaderEncoding = encoding;

            Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", (Request.Browser.Browser == "IE") ? HttpUtility.UrlEncode(fileName, encoding) : fileName));

        return File(fs, contentType, fileName);
酷炫老祖宗 2024-10-08 21:07:53

Putting

         Response.Clear();
         Response.ClearHeaders();

Before

         Response.Charset = encoding.WebName; 

为我解决了这个问题

Putting

         Response.Clear();
         Response.ClearHeaders();

Before

         Response.Charset = encoding.WebName; 

solved this for me

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文